If you like this blog, you can visit my personal blog sehgaltech for more content.
This hook is used to perform side effects in function components. Side effects could be data fetching, subscriptions, or manually changing the DOM.
useEffect takes two arguments: a function that contains the side-effect logic, and an array of dependencies. The function runs after the render is committed to the screen. If you pass an empty array ([]) as the second argument, the side effect runs once after the initial render, similar to componentDidMount in class components. If you pass a variable inside the array, the side effect runs whenever that variable changes.
Here is an example of how to use the useEffect hook:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In this example, the useEffect hook is used to update the document title whenever the count state changes. The count state is passed as a dependency to useEffect, so the effect only re-runs when count changes.
In React, "unmounting" refers to the process where a component is being removed from the DOM. This can happen when the parent component that renders the component conditionally decides not to render it, or when the user navigates away from the current page (in case of single-page apps).
The useEffect hook in React can be used to handle this unmounting process. Specifically, the function passed to useEffect can return a cleanup function. This cleanup function is executed right before the component is unmounted from the UI to prevent memory leaks.
Here's an example:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
const timerID = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 1000);
// Here's the cleanup function:
return function cleanup() {
clearInterval(timerID);
};
}, []); // Empty array means the effect runs once on mount and cleanup on unmount
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(0)}>
Reset
</button>
</div>
);
}
In this example, the useEffect hook sets up an interval that increments the count state every second. The cleanup function returned by useEffect clears the interval, ensuring that if the Example component is ever unmounted, the interval won't continue to run and try to update state on an unmounted component, which would cause a memory leak.
If you like this blog, you can visit my personal blog sehgaltech for more content.
Top comments (0)