Advertisement
Beginner React, Effects & Lifecycle

What is the useEffect hook used for in React?

Short answer

useEffect lets you run code that reaches outside of React, such as fetching data, setting a timer, or updating the page title, after a component renders. It runs after the screen updates, and you can control exactly when it runs using its dependency array.

Save React mock interview
Advertisement
AModel answer
useEffect lets you run code that reaches outside of React, such as fetching data, setting a timer, or updating the page title, after a component renders. It runs after the screen updates, and you can control exactly when it runs using its dependency array.
function PageTitle({ title }) {
  useEffect(() => {
    document.title = title;
  }, [title]);

  return <h1>{title}</h1>;
}
Real-world example
A blog automatically updates the browser tab's title to match whichever article the user is currently reading, using a simple useEffect that runs whenever the title prop changes.
Likely follow-ups
  • What happens if you leave out the dependency array entirely from useEffect?
  • Why does React run effects after the screen updates instead of before?
Related topics