Managing side effects such as data fetching, subscriptions, and manually changing the DOM can become challenging when building React applications. React’s useEffect
hook provides a powerful yet straightforward way to handle these side effects in function components. Let’s dive into the basics of useEffect
to understand how it works and when to use it.
What is useEffect
?
The useEffect
hook is a function that allows you to perform side effects in function components. It runs after every render by default, making it ideal for operations that need to happen due to state or prop changes, such as fetching data from an API or updating the document title.
Here’s a simple example:
import React, { useState, useEffect } from 'react';
const ExampleCode = () => {
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>
);
}
In this example, the document title updates every time the count
state changes. The useEffect
hook takes two arguments: a function and a dependency array. The function contains the side effect code, and the dependency array specifies when the effect should re-run. Here, document.title
is updated whenever count
changes.