When building React applications, you often need to perform actions that can affect other components or interact with external systems. These actions, known as side effects, include data fetching, subscriptions, or manually changing the DOM. Here’s where useEffect
comes into play.
useEffect
?useEffect
is a hook that manages side effects in functional components. It combines the capabilities of componentDidMount
, componentDidUpdate
, and componentWillUnmount
from class components into one API.
Here’s a simple example:
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`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect
runs after every render by default.Cleanup: If your effect returns a function, React will run this function when it’s time to clean up:
useEffect(() => {
const subscription = props.source.subscribe();
return () => {
// Clean up the subscription
subscription.unsubscribe();
};
}, [props.source]);
Dependencies: By adding a dependency array, you control when the effect runs. If you want it to run only on mount and unmount, leave the array empty []
. If it depends on some props or state, include them in the array.
Conditional Execution: Effects run after every render by default, but you might want to run them only when certain values have changed:
useEffect(() => {
if (count > 0) {
document.title = `Count: ${count}`;
}
}, [count]); // Only re-run the effect if count changes
useEffect
hooks for different side effects to keep your code clean and focused.useMemo
or useCallback
to optimize.The useEffect
hook is crucial for adding life to your React components by allowing them to interact with the outside world or react to changes within the component itself. By mastering useEffect
, you can ensure your React applications are both dynamic and efficient, handling all sorts of side effects with grace.
This guide should set you on the path to effectively using useEffect
in your React projects, making your components more interactive and responsive.