Use the useEffect
Hook whenever you need to perform side effects such as data fetching, DOM updation etc.
Key takeaways:
The useEffect
Hook enables you to perform side effects such as data fetching, DOM updates, and event handling in functional components.
By specifying dependencies in useEffect
, you can control exactly when the effect should run (on mount, state updates, or unmount, etc.).
The useEffect
Hook is ideal for data fetching from APIs, manipulating the DOM, managing timers, and handling browser events like window resizing.
useEffect
HookThe useEffect
Hook is one of React’s built-in Hooks that allows you to perform side effects in React functional components when the application mounts or when the state or prop gets updated. A side effect could include:
Data fetching from an external API.
Manipulating the Document Object Model (DOM).
Using a timer function like setTimeout()
that runs for a certain period.
Before Hooks, you would have been required to use class components to handle life cycle methods like componentDidMount
and componentDidUpdate
. The useEffect
hook replaces those life cycle methods and provides a cleaner, simpler way to manage side effects in functional components.
Practice the
useEffect
hook with hands-on experience with this project: Build a Memory Game Using React.
You should call Hooks only at the top level of the component, meaning they should not be called inside loops, conditions, or nested functions.
You should call Hooks only in React functional components or within custom Hooks. Hooks won’t work in class components or regular JavaScript functions outside the React environment.
Note: The above rules should not be regarded as the use case for only
useEffect
, but for any Hook you decide to use, even custom hooks.
useEffect
HookThe syntax to define the useEffect
Hook is as follows:
useEffect(callbackFunction, [dependencies]);
In the syntax above, we have the following:
A callback function, callbackFunction
, contains the logic that will run when the component renders or updates.
An optional dependency array, [dependencies]
. This array determines when the effect should be re-run. If it’s empty, the effect runs only once on the component mount. If state or props are listed, the effect runs whenever they change.
Note: The dependency array is optional, but how you use it drastically affects how your component behaves. For example:
If you provide an empty dependency array,
[]
, then the effect only runs once on the component’s initial render.If specific dependencies,
[dependency1, dependency2]
, are provided then the effect runs only when a value in the dependency array changes.If no dependency array is provided then the effect will run after every render.
useEffect
with an empty dependency arrayIn the example below, an empty array []
ensures the effect only runs once when the component is mounted. This use case is useful for initializing data, such as fetching user info on load. You will see Component mounted!
only once in the console.
Explore the
useEffect
Hook by implementing it in a real world use case in this project: Build the Frontend of a Financial Application Using React.
useEffect
with specific dependenciesIn the example below, the effect will only run when the items
state changes. The dependency array [items]
ensures the effect doesn’t run on every render but only when items
updates. Changes to the price
state do not trigger the effect because price
is not included in the dependency array.
On the initial render, the useEffect
logs Number of items changed to: 0
. Each time the user clicks the “Increase Items” button, the items
state changes, causing a rerender and triggering the effect.
useEffect
with no dependency arrayIn the example below, no dependency array is provided, therefore, the effect will execute every time the component renders. This includes both initial render and subsequent re-renders triggered by state updates.
Initially, "Component rendered!"
is logged when the component mounts. Every time you click the “Increase Items” or “Increase Price” buttons, the states change, causing a rerender. The useEffect
runs again after each rerender, logging the message to the console.
Apply the
useEffect
hook in a real-world scenario by working on this project: Build an Image Sharing App with MERN Stack.
useEffect
Let’s look at a simple example of how to fetch data from an API when the component mounts using the useEffect
Hook. We initialize a local state, posts
, as an empty array and then define the useEffect
Hook so that it executes after the component mounts. We then use the fetch
API to fetch posts from an API and finally convert the API response to JSON. We then update the posts
state with the fetched data.
The useEffect
Hook simplifies side effect management in React’s functional components. It provides a clean, unified way to handle API requests, DOM manipulation, timers, and event listeners. By using the dependency array, you can gain fine-grained control over when the effect should run.
Haven’t found what you were looking for? Contact Us