When to use UseEffect

  • when the component is first created
  • whenever the component is re-rendered
  • when the component is destroyed
  • when the state changes (or part of the state)
useEffect(callback[, dependencies]);

When the component is first created

If you pass in an empty array, useEffect() will be called only on the initial component creation (like componentDidMount for the class component). For example, if we wanted to make a request on creation, and fill the state, it would look something like this:

const [contents, setContents] = useState([])

useEffect(() => {
fetch(url)
.then(res => res.json())
.then(json => setContents(json))
}, [])

Whenever the component is re-rendered

If we want the useEffectcontents to run on every render, you should only pass in a callback, with no dependencies. For example, if a user is composing a message, you could send a copy of the draft to the server, so it does not get lost.

const [draft, updateDraft] = useState('')useEffect(() => {
fetch(url, {
method: 'POST',
body: draft,
})
})

When the component is destroyed

Sometimes, when you set something up on component creation, you want to remove it after destruction. For example, you may want to update a Redux variable or close a websocket upon deletion of the component. This has little to do with the second argument of the function. Instead, you return a cleanup function in the callback. Note that this will run on every re-render, prior to the re-render.

useEffect(() => {
/* do something */
const cleanup = () => {
/* delete something */
}
return cleanup
})
useEffect(() => {
const id = setInterval(() => {
console.log("This is logged to console.");
}, 5000);
const cleanup = () => clearInterval(id)
return cleanup
}, []);

When the state changes

This is probably the most common use, besides when the component mounts. If you want to create a side effect that is based on the state, you pass in one or more pieces of state (or props) that you care about.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store