Research Topic 5: React Hooks

React Hooks is a new feature in React v16.8 which make function component no stateless anymore. You can use state and life cycle in React function component now.

There are two basic hooks I used a lot. Before use them, we need to import it from React first

import React, { useState, useEffect } from 'react';

useState

useState() is similar to this.state in class component. It also combine the this.setState into single function.

Here is the example from React website how useState works:

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

The zero value in useState(0) is the initial value of this count state.

setCount(newValue) is the method that modify the state value

when using state in the return method, we don’t need to use keyword this before the state, because this is function component.

PS: There is a naming convention for the method to change state. Start with useXXX, XXX is the state name. And useXXX is the method to change XXX state

useEffect

useEffect hook is similar to a combination between componentDidMountcomponentDidUpdate, and componentWillUnmount in class component.

Here is the example from React website:

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Each time this Example component being rendered or update, the code inside useEffect() function would run. Also, you can add extra second parameter to customize when you want this function run or not.

Rule regarding using Hooks

There are some rules we need to follow if we want to use Hook in React function component.

  • Only Call Hooks at the Top Level
  • Only Call Hooks from React Functions