• Register
440 points
3

UseEffects
 

What does useEffect do?

By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates.  In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.

 

Note: Hooks cannot be Work With Class Component Hooks Always Work with functional component

 

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

 

Example:

In This is Example I want to show my count value in the title.

 

useEffect function is running after every click And showing the value in the title

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



function Example() {

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



  useEffect(() => {

    document.title = `You clicked ${count} times`;

  });



  return (

    <div>

      <p>You clicked {count} times</p>

      <button onClick={() => setCount(count + 1)}>

        Click me

      </button>

    </div>

  );

}

 

 

Now I have 2 buttons and I want to run this useEffect for an individual button then we need to use an array in useEffect Like This

useEffect(()=>{

},[num])

 

1 Comment

Informative Post:

Your topic explains “What does useEffect do?” and with example it looks just perfect, Thanks for sharing and Happy Coding!