DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on

useEffect Hook

UseEffect Hook React:

useEffect - Hook, Which can be used in Functional Component.

  • We can do API calls
  • We can Update State here
  • We have dependency Array
    • Empty [] => Called only once when component is loaded
    • [props / state] => Called everytime when prop /state changes

The useEffect hook will replace method of Class Component
-componentDidMount --> []
-componentDidUpdate --> [props/state]
-componentWillUnmount --> return ()=>{ //cleanup }


// React Importing useEffect
import React, { useEffect } from "React";


// HOOK CALLED HERE
useEffect(() => {
  // code
  // effect
  // API call
  // logic


  // return will be called only when components UNMOUNT

  return () => {
    // Cleanup timer etc.
  };
}, []);
Enter fullscreen mode Exit fullscreen mode
useEffect(() => {
  let timerId = setTimeout(() => {
    // perform an action like state update
    timerId = null;
  }, 5000);

  // clear the timer when component unmouts
  return () => clearTimeout(timerId);
}, []);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)