logo

A Short Introduction to React Hooks

The React team has released React 16.8 -- the one with hooks. It is an exciting time for the React community as this feature is going to bring a lot of benefits to all React developers.

What is it?

Hooks are tools for developers to have states and logic in dumb components / functional components that used to live in classes. I think of them as plugins for React functional components to acquire extra features. Is it a non-breaking change, it is like a plugin which you can op-in if you want to. We do not need to rewrite all our React containers to functional components to try out hooks.

Hooks: useState

useState provides a gateway to declare and update a state. It is a function that takes in a initial value for the state you are creating.

import {useState} from react;
    
// functional React component
const form = (props) => {
    const [firstName, setFirstName] = useState('');
      
    return (
        // your component
    );
};

useState returns an array with two elements. The 1st element is where you access the value of your state. The 2nd element is a function for updating the state. A empty string is the initial value for firstName.

We could have arbitrary names thanks to Array Destructing to access the array elements.

Hooks: useEffect

useEffect hook is an replacement for the React lifecycle methods — componentDidMount, componentDidUpdate and componentWillUnmount. We do not need to duplicate codes for componentDidMount and componentDidUpdate anymore! useEffect is an elegant way to achieve the same result.

The 1st argument is a function. The 2nd argument is optional, it is an array of variables which the function in the 1st argument depends on. The values of the variables are used to compare with its previous values during every render. If the values are the same, useEffect would not call the function again for optimisation. Having all the depended variables added to the array is important to achieve the best result.

import {useEffect} from 'react'
    
const carousel = (props) => {
  useEffect(() => {
    // code for componentDidMount/componentDidUpdate
        
    return () => {
       // code for componentDidUnmount
    };
  })
      
  return (
    // component
  );
};

Rules of Hooks

There are rules we need to enforce for hooks to work expectedly.

  • Do not call Hooks inside loops, conditions, or nested functions.
  • Do not call Hooks inside classes, only call them inside React functional components.

The awesome people have created an Eslint plugin to make sure that we are following the rules. More information: https://reactjs.org/docs/hooks-rules.html