useEffect() Hook in React js

 

useEffect-Hook

React's useEffect() Hook

The Effect Hook lets you perform side effects in function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount()componentDidUpdate() and componentWillUnmount() lifecycle methods.

Side-effects are things you want your application to make like:

  • Fetching data
  • Manually changing the DOM (document title)
  • Setting up a subscription

Effects will run after every render, including the first render.

useEffect is a hook for encapsulating code that has 'side effects', if you are familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined,

Ex:
import React, {useState, useEffect} from 'react';
useEffect(Function)
useEffect(Function,Array)

  • The function passed to useEffect will run after thee render is comitted to the screen
  • Second argument to useEffectt that is the array of values that the effect depends on.
  • You can call useEffects as many times as you want.


When using the the Effect Hook, we use useEffect():


        import React, { useEffect } from 'react';

    function App() {
      useEffect(() => {
        console.log('this is useEffect ');
        document.title = 'changeTitle';
      });
   
      return <div>stuff goes here</div>;
    }
     
    export default App;


Running an Effect Hook only when something changes

Since useEffect() runs every time a component renders, how do we get it to only run once, on mount? The Effect Hook can take a second argument, an array. It will look through the array and only run the effect if one of those values has changed.


componentDidMount: Runs once

        // only run on mount. pass an empty array
    useEffect(() => {
      // only runs once
    }, []);


componentDidUpdate: Runs on changes

         // only run if count changes
    useEffect(
      () => {
        // run here if count changes
      },
      [count]
    );


Hooks Effect :

The Effect Hook allows us to perform side effects in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.

Here is the clear example of useEffect() , it side effects to document.title

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

  function App() {

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

    useEffect (() => {
      document.title = `You clicked ${count} times`;
    }  
    )


    return (
      <div>
          <h1>{count}</h1>
        <button onClick={()=>setCount(count+1) }>Click {count} times</button>
   
      </div>
    );
  }

  export default App;


Hooks Effect : with array []

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

  function App() {

    var [name,setName] = useState("Code");
    var [admin,setAdmin] = useState(false);

    useEffect(()=>{
      console.log('Celebrate ${name}');
    },[name]);

    useEffect(()=>{
      console.log(
        `The use is : ${admin ? "admin" : "No admin"}`
      );
    }, [admin]);

    return (
      <div>

        <section>
          <p>Congratulations {name}</p>
          <button onClick={()=>setName("Will")}>
            Change..
          </button>
          <p>{admin ? "logged in" : "not logged in"}</p>
          <button onClick={()=>setAdmin(true)}>
            Log In
          </button>
        </section>



      </div>
    );
  }

  export default App;


API fetch using useEffect()

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

  function App() {

    var [data,setData] = useState([]);

    useEffect(()=>{
      fetch('https://api.github.com/users')
      .then ((response)=>response.json())
      .then (setData)

    },[])

    return (
      <div>

          <ul>
            {
              data.map((user)=>(
                <li key={user.id}>{user.login}</li>
              ))
            }
          </ul>

          <button onClick={()=>setData([])}>
            Remove Data
          </button>

      </div>
    );
  }

  export default App;



API 
integration with useEffect(); using Material Table:



    import React, { useState, useEffect } from 'react';
    import './App.css';
    import MaterialTable from 'material-table'


    function App() {

      const [data, setData] = useState([])
      const columns = [
        { title: "ID", field: "id" },
        { title: "Username", field: "username" },
        { title: "Name", field: "name" },
        { title: "Email", field: "email" },
        { title: "Phone", field: "phone" },
        { title: "Web Link", field: 'website' }
      ]
      useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/users")
          .then(resp => resp.json())
          .then(resp => {
            setData(resp)
          })
      }, [])

      return (
        <div className="App">
          <h1 align="center">React-App</h1>
          <h4 align='center'>Material Table</h4>
          <MaterialTable
            title="Employee Data"
            data={data}
            columns={columns}
          />
        </div>
      );
    }

    export default App;