useEffect – React

useEffect is a Hook in React that allows you to perform side effects in functional components. Side effects can include data fetching, subscriptions, or manually changing the DOM. By using useEffect, you can manage these effects in a declarative way.

Here’s a brief overview of how useEffect works and some common use cases:

Basic Usage

The useEffect Hook takes two arguments:

  1. A function (the effect) that contains the side effect logic.
  2. An optional array of dependencies that determines when the effect should be run.

Example: Basic Usage

import React, { useEffect } from 'react';

function MyComponent() {
useEffect(() => {
console.log('Component mounted or updated');
// Perform side effect here

return () => {
console.log('Cleanup if needed');
// Cleanup logic here (e.g., unsubscribing from a service)
};
}, []); // Empty dependency array means this effect runs once when the component mounts

return <div>My Component</div>;
}

Dependency Array

The dependency array is used to control when the effect should re-run. If a value inside this array changes between renders, the effect is re-executed.

Example: Effect with Dependencies

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

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

useEffect(() => {
console.log(`Count is: ${count}`);
// Effect logic here

return () => {
console.log('Cleanup');
// Cleanup logic here
};
}, [count]); // Effect runs when 'count' changes

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

Cleanup Function

The function returned from the effect function is the cleanup function. It is called when the component unmounts or before the effect is re-executed (if dependencies have changed).

Example: Cleanup

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

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

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

// Cleanup on unmount
return () => clearInterval(interval);
}, []); // Empty array means the effect runs once on mount

return <div>Seconds: {seconds}</div>;
}

Common Use Cases

  1. Fetching Data: seEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); // Fetch data once on mount
  2. Subscribing to Services: useEffect(() => { const subscription = someService.subscribe(data => setData(data)); return () => subscription.unsubscribe(); // Cleanup on unmount }, []);
  3. Updating Document Title: useEffect(() => { document.title = `Count: ${count}`; }, [count]); // Update title when 'count' changes

Important Points

  • Multiple useEffect Calls: You can have multiple useEffect calls in a single component to handle different side effects.
  • Performance: Ensure that the logic inside the effect is performant, especially if it runs frequently.
  • Dependency Array: Be mindful of what you include in the dependency array to avoid unnecessary re-renders or missed updates.

By using useEffect, you can effectively manage side effects in your React components in a clean and maintainable way.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *