Header Ads Widget

Ticker

6/recent/ticker-posts

Understanding the useEffect Hook in React (With Examples)

Understanding the useEffect Hook in React (With Examples)
Understanding the useEffect Hook in React (With Examples)

Introduction

React is a powerful library used for creating user interfaces with JavaScript, and the newer hooks have made integrating functional components even more effortless. useEffect is the most used one among them in React. Today's passage will explain what useEffect is, how it works, and how it can be used with some examples.

What is the useEffect Hook?

The useEffect Hook is utilized for side effects in the functional components. Side effects are activities required to be done after a certain action:

  • Data reception from APIs
  • DOM manipulations
  • Event subscription
  • Setting of timers or intervals

In class components, lifecycle methods received the saving grace, componentDidMount, componentDidUpdate, and componentWillUnmount were the ones behind most of that. With hooks, React bibliophiles can replace those and others with a simple, effective way in one line within the functional components. 

useEffect Basic Syntax

import { useEffect } from 'react';

useEffect(() => {
  // Your effect logic here
});

The function is called every time the component re-renders. However, such runs can be controlled by a dependency list to place as an argument. 

Example 1: Running useEffect on Every Render

If any auxiliary data is to be used, then it will trigger after a re-render.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    console.log('Component rendered or updated!');
  });

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

Explanation:

  • Every time count changes, the component re-renders.
  • useEffect, which is called after every render, will display a message in the console. 

Example 2: Run useEffect Only on Mount

To make useEffect work when the component is first rendered (like componentDidMount :), pass an empty array. 

useEffect(() => {
  console.log('Component mounted!');
}, []);

The function given inside the useEffect will run only once as the effect is invoked during the first render of the component. 

Example 3: Run useEffect When Some Value Changes

There is a way to specify values that would trigger the effect.

import { useState, useEffect } from 'react';

function Message({ message }) {
  useEffect(() => {
    console.log(`Message updated: ${message}`);
  }, [message]);

  return <p>{message}</p>;
}

Explanation:

  • So, useEffect will only run when the message prop changes. 
  • This behavior would ensure the useCallback is invoked unnecessarily when stateful update takes place.

Example 4: Cleaning Up Effects (Unmounting)

There are some effects that need to be cleaned up, like events or timers. All the clutter can be removed by returning a function from useEffect.
import { useEffect, useState } from 'react';

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

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

    return () => {
      clearInterval(interval);
      console.log('Timer stopped!');
    };
  }, []);

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

Notes:

  • A timer starts once the component is fully mounted.
  • The cleanup function stops the interval when the component unmounts.

Common Mistakes and Guiding Practices

  1. Should not forget the dependency array If there is no dependency array, useEffect is called following every execution, causing missed unnecessary re-renders.
  2. Incorrect Astute State Update State updates can cause infinite loops when triggered inside useEffect and when the state is listed in the dependencies.
  3. Clearing Up the Side Effects Always do a cleanup on the effects, especially when dealing with event listeners and intervals, so as to avoid memory leaks.
In conclusion

useEffect
is quite powerful to manage side effects in a functional component in React. Undercutting how dependencies work and knowing just when you should clean up an effect sets the foundation of how efficient and bug-free your applications are going to be in React.

A Quick Recap:

  • Run on every render: useEffect(() => {...});
  • Run only on a mount: useEffect(() => {...}, []);
  • Run when any of the dependencies change: useEffect(() => {...}, [dependency]);
  • Clean up side effects: Return a function inside useEffect.
With this knowledge of useEffect, you will now find it quite easy to manage side effects and will, consequently, beef up the premium quality of your own components. Have the best out of coding!


Frequently Asked Questions (FAQ) about useEffect

1. What does useEffect do when used in React?
useEffect is an actively used side effect intended to be specifically placed into functional components to allow for the execution of data fetching, event listeners, and DOM updates.

2. When does useEffect run?
Immediately at every rendering. The exact time is expressed by passing an optional dependency array.

3. How would useEffect be executed just once?
Supply the dependency array as an empty array to add new useEffect to the above statement.

4. How can I clean up after an effect executed in useEffect?
When you throw the return statement in useEffect, indicating a manual clean-up of event listeners, timers, or subscriptions should be performed before the component unmounts.

5. What will be the impact or consequence of not including the dependency array?
The effect will be going on after rendering without an end, causing lots of vibration in the performance epitome in many cases and, in turn, an infinite loop.

6. Is it okay to wrap one component in multiple useEffect hooks? 
Yes, with relative ease, the use of various useEffect hooks for separate logic concerns within individual components.


Post a Comment

0 Comments