Source: Joseph Mawa.What is useEffect hook and how do you use it?30 June 2020

To discuss

  • introduce
  • What parameters are passed by useEffect Hook?
  • UseEffect is the first parameter
  • The return value of effect
  • UseEffect is the second parameter
  • Pass a function as a dependency
  • reference

This is my third article in the React Hook series. If you haven’t seen the first two, follow the links below.

  1. What is useState hook and how do you use it?
  2. What is useReducer hook and how do you use it?

UseEffect hook profile

A hook is a function that lets you use states and other React features without writing ES6 classes. The useEffect hook is part of the React Hook API. If you’re familiar with the React lifecycle, the useEffect hook is equivalent to a combination of the lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount. According to the React documentation, the useEffect hook was developed to address some of the challenges posed by the lifecycle methods of ES6 class components. Since this article is about what Effect Hook is and how it is used, I won’t say why it was developed. You can check it out here. In the React feature, we use the useEffect hook to perform “side effects” such as fetching data from the API or manually updating the DOM.

What parameters are passed by useEffect Hook?

UseEffect is a function that takes two arguments. The first argument passed to useEffect is a function named effect (you can guess why the hook is called useEffect), and the second argument (optional) is an array that stores dependencies. Here’s how it works.

import React, { useEffect } from "react";
import { render } from "react-dom";
const App = props= > {
  useEffect(() = > {
    console.log("Effect has been called");
  }); //Second argument to useEffect has been omitted
  return <h1> Hello world! </h1>;
};  
const root = document.getElementById("root");
render(<App />, root);
Copy the code

UseEffect is the first parameter

The first argument, called effect, is a function that returns either a function (called cleanup) or undefined. Effect is executed when the component is mounted (the first rendering), and whether it is executed in subsequent updates is determined by the array of dependencies passed as the second argument.

effectParameter return value

In the previous section, we said that the first argument to useEffect is a function named effect. Effect requires no parameters and must return a function or undefined function. If it returns a function, the return function is called cleanup. Cleanup is performed before calling effect (to cleanup previously rendered effects). If you’re curious about why and when you need to clean up, check out the React documentation for an explanation. Since an effect returns either a function or undefined, it’s not uncommon to have an effect without cleanup.

UseEffect is the second parameter

The second argument to useEffect is an array of dependencies. If you want to control when effect is executed after a component is mounted, pass an array of dependencies as the second argument. Dependencies are values defined outside useEffect but used inside useEffect, such as.

     function App(){
         const[state, setState] = useState(0);
          // state is defined here
         useEffect(() = > {
              console.log(state); 
              //value of state is used here therefore must be passed as a dependency
         }, [state])

     }
Copy the code

React compares the current value of the dependency to the previously rendered value. If they are different, effect is called. This parameter is optional. If omitted, effect will be executed after each render. If you want effect to be executed only on the first render, you can pass an empty array.

     useEffect(() = > {
       console.log("Effect has been called");
}, []) // Empty array as dependency, useEffect is invoked once
Copy the code

Dependencies can be either state or props. It is important to note that any value defined outside of useEffect and inside the component must be passed as a dependency if you want to use it inside useEffect. This point is explained below.

  function App(props) {
     const [count, setCount] = React.useState(1);
     // count and setCount are defined inside component(App) but outside useEffect
     useEffect(() = > {
       //count is being used inside useEffect. Therefore must be passed as dependency.
       console.log(count);
}, [count])
}
Copy the code

Pass a function as a dependency

You might be wondering, if you define a function outside of useEffect and then call it inside effect, do you need to pass it as a dependency? Let me give you an example.

 function App(props){
    const [data, setData] = useState(null);
    const fetchData = () = > {
         //fetch some data 
    }
    useEffect(() = > {
    fetchData(); //Invoked inside useEffect
}, [fetchData])

}
Copy the code

It is not recommended to define a function outside and then call it inside effect, as above. The above situation results in fetchData being called on every render, because the dependency passed is a function, and functions are objects. React compares the last rendered fetchData to the current rendered data, which is different, and thus triggers the call to Effect.

UseEffect hook according to the section in the React documentation

It is difficult to remember which functions or states are used by functions other than effect. This is why you usually want to declare the required functions inside Effect. This makes it easy to see which values are in the component scope on which the effect depends. You can also move the function inside effect so that it doesn’t need to be in the dependency list.

reference

  • React Hooks FAQ
  • Hooks API Reference
  • Complete guide to React