0
0
Reactframework~5 mins

What is useEffect in React

Choose your learning style9 modes available
Introduction

useEffect helps your React component do things after it shows up on the screen or when something changes. It's like telling your app to react to changes or do side jobs.

Load data from the internet when a page opens
Update the page title when a user changes something
Set up a timer or interval that runs repeatedly
Clean up resources like stopping a timer when the component goes away
Syntax
React
useEffect(() => {
  // code to run
  return () => {
    // cleanup code (optional)
  };
}, [dependencies]);

The first argument is a function that runs after the component renders.

The second argument is an array of dependencies that tell React when to run the effect again.

Examples
This runs after every time the component renders.
React
useEffect(() => {
  console.log('Runs after every render');
});
Empty array means it runs only once when the component first appears.
React
useEffect(() => {
  console.log('Runs only once when component mounts');
}, []);
This runs only when the count value changes.
React
useEffect(() => {
  console.log('Runs when count changes:', count);
}, [count]);
Sample Program

This component shows seconds passed since it appeared. It uses useEffect to start a timer when the component mounts and cleans it up when it unmounts.

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

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

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

    return () => clearInterval(interval); // cleanup on unmount
  }, []);

  return (
    <div>
      <p>Seconds passed: {seconds}</p>
    </div>
  );
}

export default Timer;
OutputSuccess
Important Notes

Always clean up timers or subscriptions inside useEffect to avoid bugs.

If you forget the dependency array, the effect runs after every render, which can slow your app.

Summary

useEffect runs code after rendering or when data changes.

Use it to load data, update things, or clean up resources.

Remember the dependency array controls when it runs.