React useEffect()

The useEffect hook
useEffect is a hook meant to be used when you want to perform side effects.
Manually changing the DOM or fetching data are examples of this.
By default, this hook runs after each render, which means that every time React sees the need to rerender.
useEffect(callback, [dependencies]);
The useEffect Hook Usages
The callback function we pass to the useEffect hook runs the side effects. React runs it on every render of a component by default. However, side effects can be expensive and performance-intensive to run on every render. We can control it using the dependency array argument we pass to the useEffect hook.
In this section, we will learn six usages of useEffect hook to run and clean up a side effect.
1. Side Effect Runs After Every Render
The first is the default case. If you do not pass the dependency array to the useEffect hook, the callback function executes on every render. Thus React will run the side effect defined in it after every render.
COPY
useEffect(() => {
// Side Effect
});
It is not a highly used use case scenario. We may always want to control the run of a side effect.
2. Side Effect Runs Only Once After Initial Render
You may want to run the side effect just once after the initial render. A typical case will be fetching data making an API call, and storing the response in the state variable after the initial render. You do not want to make this API call again.
You can pass an empty array as the second argument to the useEffect hook to tackle this use case.
COPY
useEffect(() => {
// Side Effect
}, []);
In this case, the side effect runs only once after the initial render of the component.
3. Side Effect Runs After State Value Changes
You may need to run a side effect depending on a state value. For example, you may have a side effect to prepare a greeting message based on a spoken language(English, Spanish, Hindi, Tamil, etc.). Here the spoken language value is stored in a state variable.
Every time we select a spoken language, the state gets updated. As the state value gets updated, you want to recreate the greeting message. To solve this use case, you must pass the state variable to the useEffect hook as part of the dependency array.
COPY
useEffect(() => {
// Side Effect
}, [state]);
In this case, the side effect will run every time the value of the state variable changes. If multiple state variables influence a side effect, you can pass them as comma-separated in the dependency array.



