React is a JavaScript-based user interface library. React components are isolated reusable pieces of code logic with their own UI. Multiple components come together to create a meaningful working React application.
We can create components in two ways, using a class or a function. With the simplicity and greater exposure of functions to JavaScript developers, we see many React developers adapting to function-based components over class-based ones.
Since React version 16.8, React got an exciting new feature called Hooks. React provides many standard in-built hooks to manage states, isolate side effects, create references, improve performance, etc. We can also create custom hooks, which are just JavaScript functions with access to many React features.
In this article, we will talk about one of the most-used in-built React Hook called useEffect
. We will learn the usage of it with practical use cases.
The useEffect Hook
The outcome from a Component is to render "something" on the user interface with the rendering logic(written in JSX). Many factors drive the rendering logic,
- The state values are defined and updated inside a component.
- The props values are passed to the component.
- The side effects.
Now, what are the side effects
? It is okay if you haven't heard it before in the context of programming. Let us break it and understand here.
- A side-effect can be any effect(programming logic) that is responsible for changing the state of your component. If the state changes, the component re-renders. For example, a typical side effect is making an API call and changing the local state of a component to store the API response data.
- Also, there could be side-effects that may not update state values and don't influence the rendering logic. For example, you log a text on the browser console or store something in the browser's localstorage. Please note, some of these we can do using the
useRef
hook as well that we will learn in the future article.
So, a side effect is something that we should isolate from the rendering. The useEffect
hook helps perform side effects by isolating it from the rendering logic.
useEffect(callback, [dependencies]);
The useEffect hook takes two arguments,
- A callback function to define and clean up a side effect.
- An optional dependency array that ensures when to run a side effect defined inside the callback function.
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.
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.
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.
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.
useEffect(() => {
// Side Effect
}, [state1, state2, state3]);
4. Side Effect Runs After Props Value
Change
Just like the state, we can also use props as a dependency to run the side effect. In this case, the side effect will run every time there is a change to the props passed as a dependency.
useEffect(() => {
// Side Effect
}, [props]);
You can pass multiple props as comma-separated as dependencies like the previous example.
5. Side Effect Runs After Props and State Value
Change
What if you need to run the side effect every time a combination of state and props change. This use case may occur when your side effect depends on the state and props values. In this case, you need to pass both the state and props variables as dependencies.
useEffect(() => {
// Side Effect
}, [props, state]);
6. Side EffectCleanup
So far, we have seen how and when to run a side effect. It is also essential that we clean up the side effect to taking care of the application's performance. Every side effects are different. So, the cleanup strategy for the side effect will differ.
For example, if you have a side effect of running a timer using the setTimeout
function, you need to clean it up by invoking the clearTimeout
function. But how do we do it?
To clean up a side effect, you need to return a function from the callback function we pass to the useEffect hook. You must place the side effect clean up logic inside the returned function.
useEffect(() => {
// Side Effect
return () => {
// Side Effect Cleanup
}
}[props, state]);
A few points to note,
- The cleanup function gets invoked every time after the initial render to clean up the previous side effect, and then the subsequent side effect runs.
- The cleanup function gets invoked when the component unmounts.
Conclusion
So that's all about usages of the useEffect
hook. I hope you found the article informative and helpful.
But wait, that's not all, really! If you want to continue to learn about it practically with a hands-on project, I'll leave you with this YouTube video tutorial. I hope you enjoy it as well.
Please SUBSCRIBE for the future content 🔥🔥🔥
Before We End...
I share my knowledge on,
- 🌐 Web Development(JavaScript, ReactJS, Next.js, Node.js, so on...)
- 🛡️ Web Security
- 💼 Career Development
- 🌱 Opensource
- ✍️ Content Creation
Let's connect,
Top comments (2)
One thing I need to point out is useEffect will always run on mount
So
Side Effect Runs After X Value Change
is kinda misleadingOne issue you might face is to make some custom component with 2 way binding with some form lib(like react hook form
You'll found that the input field is always dirty in the form state
Its because the onChange will not only fire on value change but also on mount
Thanks, Mark ✌