0
0
Reactframework~5 mins

Multiple effects in a component in React

Choose your learning style9 modes available
Introduction

Sometimes a component needs to do different jobs when it changes. Using multiple effects helps keep these jobs separate and clear.

When you want to fetch data from a server and also listen to user input changes.
When you need to update the document title and also log something to the console at different times.
When you want to run one effect only once when the component loads and another effect every time a value changes.
Syntax
React
useEffect(() => {
  // first effect code here
}, [dependencies1]);

useEffect(() => {
  // second effect code here
}, [dependencies2]);
Each useEffect runs independently and can watch different values.
You can have as many useEffect hooks as you need inside one component.
Examples
The first effect runs only once when the component appears. The second runs every time the count value changes.
React
useEffect(() => {
  console.log('Runs once on mount');
}, []);

useEffect(() => {
  console.log('Runs when count changes:', count);
}, [count]);
The first effect updates the page title when count changes. The second effect runs after every render.
React
useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]);

useEffect(() => {
  console.log('Component updated');
});
Sample Program

This component has two separate effects. One logs when the count changes. The other logs when the name changes. This keeps the logic clear and easy to manage.

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

function MultiEffectExample() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');

  useEffect(() => {
    console.log('Count changed:', count);
  }, [count]);

  useEffect(() => {
    console.log('Name changed:', name);
  }, [name]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase Count</button>
      <p>
        Name: <input value={name} onChange={e => setName(e.target.value)} aria-label="Name input" />
      </p>
    </div>
  );
}

export default MultiEffectExample;
OutputSuccess
Important Notes

Each effect can watch different values and run independently.

Keep effects focused on one job to make your code easier to understand.

Remember to add dependencies to avoid running effects too often or too little.

Summary

Multiple effects let you separate different side jobs in a component.

Each useEffect can watch its own values and run when those change.

This makes your component easier to read and maintain.