Hooks are a new addition in
React 16.8
. They let you use state and other React features without writing a class.
In our previous article, we explored the useState(), hook in React, and now it's time to dive into another fundamental concept: the useEffect()
hook. React introduced hooks in version 16.8
, providing a way to utilize state and other React features within functional components without the need for class-based components. But useEffect()
can be a bit tricky to grasp initially. Don't worry; we're here to simplify it for you! 😃
What is the useEffect Hook ❓
The useEffect()
hook is a crucial part of React development. It allows us to perform side effects within our functional components. But what exactly are side effects? 🤔
In programming, side effects refer to actions taken by a function that are not predictable based solely on its inputs. In simpler terms, a function has side effects when it alters something beyond its own scope. With useEffect()
, you can carry out various tasks, such as data fetching through APIs, that have side effects on your application.
React's useEffect
function operates within three distinct lifecycles of a component:
componentDidMount: This phase occurs when the component is initially rendered and added to the DOM.
componentDidUpdate: It comes into play whenever the component updates or re-renders.
componentWillUnmount: This phase triggers when the component is about to be removed from the DOM.
Understanding these lifecycles is vital because useEffect()
enables us to respond to changes in the component lifecycle.
Read this to Understand how useEffect() in Relation to Component Lifecycle
How to Use useEffect 🔄
The useEffect
hook requires two arguments:
The first argument is a callback function containing the code you want to execute. This code represents the side effects you intend to create. React executes this callback after rendering the component.
The second argument is an
optional
array of dependencies. Whether you include it or not depends on when you want theuseEffect
hook to execute the callback function. If you include properties in this array,useEffect
will only run when those properties change.
Here's the basic syntax:
useEffect(callback, [dependencies]);
Let's break it down:
- First, import
useEffect
from React:
import { useEffect } from 'react';
- Then, use
useEffect
in your component:
function MyComponent() {
useEffect(() => {
// Your code for side effects goes here.
}, [dependencies]);
// ...
}
useEffect Dependency Options 🎯
Depending on how you set up the second argument, you have three options with different behaviors:
No dependencies:
useEffect(() => { // Code that runs after each render });
This option is not commonly used, but it can be helpful in situations where you need to perform heavy calculations after every render.
Empty dependencies array:
useEffect(() => { // Code that runs once after mounting and the first render }, []);
This is ideal for one-time effects, such as setting up event listeners or fetching data that only needs to happen once during component initialization.
With dependencies array:
useEffect(() => { // Code that runs when any dependency (a, b, c) changes }, [a, b, c]);
This option allows you to trigger the effect when specific dependencies (props or state) change, making it useful for tasks like fetching new data when certain values update.
A Simple Counter Example using useEffect
:
Let's put it all together with a straightforward example:
import React, { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Counter;
In this example, we use useEffect
to update the document title whenever the count
state changes. This is a simple illustration of how useEffect
can be used to respond to changes in your component.
Cleanup in useEffect 🧹
Now, let's dive into the cleanup aspect of useEffect
. Cleanup is like tidying up after you've finished using something. In React, it's essential to clean up any side effects created by an effect to prevent issues and maintain a clean codebase.
To include cleanup in useEffect
, you can return a function inside the effect's callback. React will call this function when the component unmounts (i.e., is removed from the screen) or when the dependencies change, just before running the effect again.
Here's an example that includes cleanup:
codeuseEffect(() => {
// Setup code for the effect
// Cleanup function
return () => {
// Cleanup code here
};
}, [dependencies]);
Now let's implement the cleanup
on our counter-example :
import React, { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
// if the count is greater than 0 then only the title going to change.
if(count>0){
document.title = `You clicked ${count} times`;
}
return () => {
// Cleanup code here
document.title = "React APP";
};
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Counter;
This code is a React component that tracks a counter (count
) and updates the document's title to display how many times a button has been clicked (if the count is greater than 0). It also includes a cleanup function to reset the document title when the component unmounts or when the count
value changes.
Conclusion 💥🙌
The useEffect
hook in React brings the functionality of lifecycle methods to functional components, simplifying the development process. Think of it as a combination of componentDidMount
, componentDidUpdate
, and componentWillUnmount
rolled into one.
To become a proficient React developer, it's essential to master the useEffect
hook and understand its underlying design concepts and best practices. With this knowledge, you'll be well-equipped to build robust and responsive React applications.
Thanks for reading all the way to the end! 💖
If you have any questions, please use the comments section 💬
Let's connect! Find me on the web 🔗
If you have any Queries or Suggestions, feel free to reach out to me.
Happy Coding :)❤️