concept effect function in category react

appears as: effect function, n effect function, effect functions, effect functions, An effect function
React Hooks in Action

This is an excerpt from Manning's book React Hooks in Action.

The component uses a randomly generated index to pick a greeting from an array. Whenever the updateGreeting function calls setIndex, React re-renders the component (unless the index value doesn’t change). React runs the effect function within the useEffect hook after every render, updating the page title as required. Notice that the effect function has access to the variables within the component because it’s in the same scope. In particular, it uses the values of the greetings and index variables. Figure 5.2 shows how you pass an effect function as the first argument to the useEffect hook.

Figure 5.2 Passing an effect function to the useEffect hook.
  • Wrap side effects inside an effect function as the first argument to the useEffect hook:
  • useEffect(() => {
      // perform effect
    });

    React runs the effect function after every render.

  • To manage when an effect function runs, pass a dependencies array as the second argument to the useEffect hook.
  • Pass an empty dependencies array to make React run the effect function once, when the component mounts:
  • useEffect(() => {
      // perform effect
    }, []);
  • Include all of the effect function’s dependencies in the dependencies array to make React run the effect function whenever the values of the specified dependencies change.