36
useEffect Hook
The useEffect hook is used to handle the side effect of React functional components outside of returning JSX. For instance, fetch data from an API when a component loads. Another example consists of starting or stopping a timer. Also, the useEffect allows to make manual changes to the DOM.
Any code defined inside the useEffect hook will run after React components finished the DOM updates. By default, useEffect runs both after the first render as well as whenever the component's state updates.
The default behavior of useEffect does not always agree with the purpose of our code. To adjust this behavior, we can run useEffect hook functions conditionally using dependencies array.
for Example, we only need to run a fetch call to an API once after the JSX has completely loaded. Adding an empty dependencies array as a second argument to the useEffect function will stop the fetch call to API from happening with every re-render of the components. Therefore, the fetch call will only occur when the component renders for the first time.
Using the example of an incrementing counter running as a side effect. We can add the counter variable to the dependencies array. Therefore, the useEffect will run every time our counter state changes.
36