React useEffect

Run side effects: timers, subscriptions and fetching.

✍️ 3 exercises + code challenge in this lesson

useEffect runs code after rendering, for things outside React: timers, data fetching, subscriptions, document title.

useEffect(() => { ... return cleanup; }, [dependencies]);

  • []: run once after the first render.
  • [value]: run again whenever value changes.
  • Return a cleanup function to stop timers or listeners when the component unmounts.

Key Takeaways: React useEffect

Mastering React useEffect helps you write clean and reliable React code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

React useEffect Code Example

React
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.25.6/babel.min.js"></script>

<script type="text/babel">
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;
function Clock() {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    const id = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(id);   // cleanup
  }, []);

  return <h2>{time.toLocaleTimeString()}</h2>;
}

function App() {
  const [show, setShow] = useState(true);
  const [clicks, setClicks] = useState(0);

  useEffect(() => {
    document.title = `Clicked ${clicks} times`;
  }, [clicks]);

  return (
    <div>
      <button onClick={() => setShow(!show)}>{show ? "Hide" : "Show"} clock</button>{" "}
      <button onClick={() => setClicks(clicks + 1)}>Clicks: {clicks}</button>
      {show && <Clock />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
Free sign-in required · Google login available

React useEffect Practice Exercises

Check what you learned in “React useEffect”.

/ 3 solved
Fill in the blank

Run code after rendering (here only once, because of the empty array).

(() => { load(); }, []);
✓ Correct! Not quite. Try again.
Multiple choice

What should an effect return to clean up a timer?

✓ Correct! Not quite. Try again.
Code challenge

Use useEffect to set document.title to "Dashboard".

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services