How to Use the useEffect React Hook
Discover the usefulness of the useEffect React hook and learn how to work with it!
If you’re new to React hooks, I recommend checking out my React hooks introduction first.
One of the React hooks that is commonly used is useEffect
.
1 | import React, { useEffect } from 'react' |
The useEffect
function is executed when the component is first rendered and on every subsequent re-render or update.
React first updates the DOM, then calls the function passed to useEffect()
.
Here’s an example of how to use the useEffect
hook:
1 | const { useEffect, useState } = React |
A tip for old-time React developers: If you’re used to componentDidMount
, componentWillUnmount
, and componentDidUpdate
events, the useEffect
hook replaces those.
You can optionally return a function from the function passed to useEffect()
:
1 | useEffect(() => { |
The code inside the returned function will execute when the component is unmounted, allowing you to perform any necessary cleanup.
Similar to componentWillUnmount
, you can specify cleanup logic using this return function.
useEffect()
can be called multiple times, which is useful for separating unrelated logic.
To optimize performance, you can tell React to skip executing the function by adding a second parameter—an array that contains a list of state variables to watch for. React will only re-run the side effect if one of the items in this array changes.
Here’s an example:
1 | useEffect( |
Furthermore, you can instruct React to execute the side effect only once, during mount time, by passing an empty array:
1 | useEffect(() => { |
This technique is often used and is quite handy.
For a live example of using the useEffect hook, you can check out the following CodePen: React Hooks example #3 side effects by Flavio Copes.
Tags: React hook, useEffect, side effects