Lesson 26 of 3087%

(Progress persistence is disabled until Phase 9)

React
Beginner

useEffect

Synchronizing your component with external systems.

useEffect lets you perform “side effects” in your components. Examples include fetching data from an API, setting up a subscription, or manually changing the DOM.

It runs after the component renders.

import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);

    // Cleanup function runs when the component unmounts
    return () => clearInterval(interval);
  }, []); // The empty array is the dependency array!

  return <div>Timer: {seconds}s</div>;
}
Try It Yourself

Lesson Progress

Practice This TopicTake QuizBuild a React Project

Ready to practise?

Apply what you learned with a hands-on challenge.

Practise This Topic