Hooks: useEffect
Chithra Priya

Chithra Priya @chithra_priya

Joined:
Apr 29, 2025

Hooks: useEffect

Publish Date: Jun 26
0 0

useEffect:

  • useEffect is one of the hooks concept in React.
  • The useEffect Hook allows you to perform side effects in your components.
  • Some examples of side effects are: fetching data, directly updating the DOM, and timers.
  • useEffect accepts two arguments.
useEffect(<function>, <dependency>)
Enter fullscreen mode Exit fullscreen mode

Syntax:

useEffect(() => {
    // Code to run on each render
    return () => {
        // Cleanup function (optional)
    };
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

Effect function: This is where your side effect code runs.
Cleanup function: This optional return function cleans up side effects like subscriptions or timers when the component unmounts.
Dependencies array: React re-runs the effect if any of the values in this array change.

Controlling side effects in useEffect:

1.No dependency passed:
To run useEffect on every render do not pass any dependency

useEffect(() => {
  //Runs on every render
});
Enter fullscreen mode Exit fullscreen mode

2.An empty array:
To run useEffect only once on the first render pass any empty array in the dependecy

useEffect(() => {
  //Runs only on the first render
}, []);
Enter fullscreen mode Exit fullscreen mode

3.dependency array:
To run useEffect on change of a particular value. Pass the state and props in the dependency array

useEffect(() => {
  //Runs on the first render
  //And any time any dependency value changes
}, [prop, state]);
Enter fullscreen mode Exit fullscreen mode

Table:

| Type                          | When It Runs                     | Common Use Cases              |
| ----------------------------- | -------------------------------- | ----------------------------- |
| `useEffect(() => {})`         | After **every render**           | General side effects          |
| `useEffect(() => {}, [])`     | **Only once** after first render | Fetch data, setup             |
| `useEffect(() => {}, [a, b])` | When **`a` or `b` changes**      | Sync with state/props changes |
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment