🎓 A1Learner
🔍
0 of 50 lessons completed

useEffect

useEffect is a Hook that runs work after a component renders. That work can set a page title or start a timer.

An effect after render

The function runs after the component renders.

useEffect(() => {
  console.log('The component rendered');
}, []);

Watching a value

The effect runs again when count changes.

useEffect(() => {
  document.title = `Count is ${count}`;
}, [count]);

Running one time

An empty list means the effect runs one time.

useEffect(() => {
  console.log('One time only');
}, []);

Example

import { useState, useEffect } from 'react';
export default function App() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `Count is ${count}`;
  }, [count]);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Add one</button>
    </div>
  );
}

Key points

  • An effect is work that runs after a component renders.
  • useEffect takes a function that holds that work.
  • The second argument is a list of values to watch.
  • The effect runs again when a watched value changes.

In this example, the component calls useState at the top. The call makes a count that starts at zero. The useEffect call follows it and sets the page title after the component renders. The list with count tells the effect to run again when count changes. The first render shows the count at zero before any effect runs.

Note

The first render shows the starting state before any effect runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When does an effect run?