Developer's guide to React useEffect

Last updated June 22, 2021 by Jacob Paris

A pure component only interacts with itself and its children. Any time you need to interact with the world outside your component, you are dealing with side-effects.

React gives us a handy hook for dealing with these. the React.useEffect hook lets us specify a function that deals with external forces, provide a second function to clean up after it, and drop a list of dependencies so we can re-run the effect when one of the dependencies change.

Updating the page title

This effect will run the first time the component is rendered, and then only ever run again if the title has changed.

1const [title, setTitle] = React.useState('Hooks 101')
3React.useEffect(() => {
4 document.title = title
5}, [title])

Fetching data from an API into local state.

Since our state changing will not affect the list of products that is returned, we can pass an empty array [] as our dependency so that the effect will only run when the component is first mounted.

1const [products, setProducts] = React.useState([])
3React.useEffect(() => {
4 getProducts().then((products) => {
5 setProducts(products)
6 })
7}, [])

Fetching data from an API into local state, based on a query.

If we have a query or filter to modify the set of API data we want, then we can pass it as a dependency to make sure that React runs this effect every time the component renders using a new query.

1const [products, setProducts] = React.useState([])
2const [query, setQuery] = React.useState('')
4React.useEffect(() => {
5 getProducts({name: query}).then((products) => {
6 setProducts(products)
7 })
8}, [query])

Dispatching a Redux action.

If your GET action already reduces into your Redux state, then you don't need to maintain any of that locally.

By passing products.length as a dependency, you only run this

1const dispatch = Redux.useDispatch()
2const products = Redux.useSelector((state) => state.products)
4React.useEffect(() => {
5 dispatch(GetProducts())
6}, [])

Further Reading