0
0
Reactframework~5 mins

Effect execution timing in React

Choose your learning style9 modes available
Introduction

Effects let your React components do extra work like fetching data or updating the page. Knowing when effects run helps you control your app's behavior smoothly.

When you want to fetch data right after a component appears on the screen.
When you need to update the page title or document after some data changes.
When you want to set up or clean up timers or subscriptions as components mount or unmount.
When you want to run code only once when the component loads.
When you want to run code every time some specific data changes.
Syntax
React
useEffect(() => {
  // code to run
  return () => {
    // cleanup code
  };
}, [dependencies]);

The function inside useEffect runs after the component renders.

The optional dependencies array controls when the effect runs again.

Examples
This effect runs after every render because there is no dependencies array.
React
useEffect(() => {
  console.log('Runs after every render');
});
This effect runs only once because the dependencies array is empty.
React
useEffect(() => {
  console.log('Runs only once after first render');
}, []);
This effect runs only when the count value changes.
React
useEffect(() => {
  console.log('Runs when count changes:', count);
}, [count]);
This effect sets a timer once and cleans it up if the component unmounts.
React
useEffect(() => {
  const timer = setTimeout(() => {
    console.log('Timer done');
  }, 1000);
  return () => clearTimeout(timer);
}, []);
Sample Program

This component shows a count and a button to increase it. The effect runs after the count changes, updates the page title, and logs messages. It also cleans up before running again.

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

function TimerComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('Effect runs: count is', count);
    document.title = `Count: ${count}`;

    return () => {
      console.log('Cleanup for count', count);
    };
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

export default TimerComponent;
OutputSuccess
Important Notes

Effects run after the browser paints the screen, so they don't block showing the UI.

Always include dependencies to avoid running effects too often or missing updates.

Cleanup functions help avoid bugs like memory leaks or duplicated timers.

Summary

Effects run after rendering to do extra work.

Dependencies array controls when effects run again.

Cleanup functions run before the effect re-runs or component unmounts.