ReactJS useEffect Hook

ReactJS useEffect Hook

What is useEffect hook in React?

The useEffect in ReactJS is used to handle the side effects such as fetching data and updating DOM. This hook runs on every render but there is also a way of using a dependency array using which we can control the effect of rendering

Why choose useEffect hook?

useEffect hook is used to handle side effects in functional components, such as fetching data, updating the DOM, and setting up subscriptions or timers. It is used to mimic the lifecycle methods of class-based components. The motivation behind the introduction of useEffect Hook is to eliminate the side effects of using class-based components. For example, tasks like updating the DOM, fetching data from API end-points, setting up subscriptions or timers, etc can lead to unwarranted side effects. Since the render method is too quick to produce a side-effect, one needs to use life cycle methods to observe the side effects.

How does it work?

  • You call?useEffect?with a callback function that contains the side effect logic.
  • By default,?this function runs after every render of the component.
  • You can optionally provide a dependency array as the second argument.
  • The effect will only run again if any of the values in the dependency array change.


Importing useEffect hook

To import the useEffect hook, write the following code at the top level of your component

import { useEffect } from "react";        


Let's use a timer as an example.

import { useEffect, useState } from "react";

const Counter = () => {
  const [count, setCount] = useState(1);

  useEffect(()=>{
    let timer = setInterval(()=>{
      setCount(count +1)
    },1000)
  },[count])

  return (
    <>
      <h1>{count}</h1>
    </>
  );
};

export default Counter;        

But wait!! It keeps counting even though it should only count once!

useEffect runs on every render. That means that when the count changes, a render happens, which then triggers another effect.

This is not what we want. There are several ways to control when side effects run.

We should always include the second parameter which accepts an array. We can optionally pass dependencies to useEffect in this array.


Example

1. No dependency passed:

useEffect(() => {
  //Runs on every render
});        

Example

2. An empty array:

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

Example

3. Props or state values:

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

Effect Cleanup

Some effects require cleanup to reduce memory leaks.

Timeouts, subscriptions, event listeners, and other effects that are no longer needed should be disposed.

We do this by including a return function at the end of the useEffect Hook.


import { useEffect, useState } from "react";

const Counter = () => {
  const [count, setCount] = useState(1);

  useEffect(()=>{
    let timer = setInterval(()=>{
      setCount(count +1)
    },1000)
return () =>{
      clearInterval(timer)
    }
  },[count])

  return (
    <>
      <h1>{count}</h1>
    </>
  );
};

export default Counter;        

Above code adding

return () =>{
      clearInterval(timer)
    }        

this line of code makes cleanup of every previous event that make a program run smoothly.



Fetching data from API using useEffect hook

import ProductCard from "../../UI Components/ProdutCard";
import { useEffect, useState } from "react";

const DisplayProduct = () => {
  const [products, setProducts] = useState([]);

  async function fetchProducts() {
    try {
      const url = await fetch("https://fakestoreapi.com/products");
      const data = await url.json();
      setProducts(data);
    } catch (e) {
      console.log("Data fetch error:", e);
    }
  }

  useEffect(() => {
    fetchProducts();
  }, []);

  return (
    <div className="container-fluid">
      <div className="row row-cols-1 row-cols-md-4 g-4">
        {products.map((product, index) => (
          <ProductCard
            key={index}
            image={product.image}
            price={product.price}
            title={product.title}
            description={product.description}
          />
        ))}
      </div>
    </div>
  );
};

export default DisplayProduct;        


Thank You So Much Bikash Karki Sir


#LearningReact #MERN #NMC #Day7 #React

要查看或添加评论,请登录

Yujan Ranjitkar的更多文章

社区洞察

其他会员也浏览了