React Hooks - UseEffect() - Complete introduction about react useEffect hook
Categories - React Js Tags - React Js JavaScript   Maniruzzaman Akash   4 months ago   569   0

React Hooks - UseEffect() - Complete introduction about react useEffect hook

What is useEffect Hook:
If anything changes happend and needs side effect on your component then useEffect hook will be called.

Means - when Component 

  1. Mounts,
  2. Unmount,
  3. Variable change,
  4. State change,
  5. Props change or
  6. any value changes of component, then this effect hook will work.

UseEffect hook expects a function to do something inside of it.

 

Motivation of React useEffect() Hook

When we used in class based component. Some things we need to repeat our code. Like think of a counter app, which counts value should implement in two sections like -

  1. componentDidMount() and
  2. componentDidUpdate()
  3. componentWillUnmount()

 

Look the example that in class based component - 

import React, { Component } from React;
// ...

class Score extends Component{

 this.state = {
   score: 0
 }

  componentDidMount() {
    // Search from API or process here...
    document.title = "Current Score: " + this.state.score;
  }

  componentDidUpdate() {
    document.title = "Current Score: " + this.state.score;
  }

  render() {
    return `Final Score: {this.state.score}`;
  }

}

 

To mitigate these issues in class based component

  1. Remove redundant code and
  2. Make same functionality in one place,

useEffect arrived in react. And it has also many more benefits. Let's dive into React useEffect().

 

How to create a basic useEffect Hook:

 

import { useEffect } from 'react'; 

useEffect(() => {
   // Do your logic
});

 

Key points of useEffect Hook -

 

useEffect() Render Every time

It can accept additional n number of params in it's callback function's second argument.

Argument = [] 

  1. Empty array - Render only single time in its life lifecycle
  2. Used in - Select box Options data,
  3. Used in - Static data which will not change during render

Example Code View - 

useEffect(() => {
   // Do your logic for first render
}, []);

 

Example with database call and set data -

useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos')
        .then(response => response.json())
        .then(json => setTodos(json)); // setTodos() is a function to set todos
}, [])

 

Any other argument = [loggedIn]

  1. Changes only when loggedIn change
  2. Single Data

Example Code view - 

useEffect(() => {
   // Do your logic for only when loggedIn changes
}, [loggedIn]);

 

Multiple data with comma

  1. [loggedIn, loggedMessage]

Example code view - 

useEffect(() => {
   // Do your logic for only when loggedIn and loggedInMessage changes
}, [loggedIn, loggedInMessage]);

 

When to use multiple useEffect Hook:

In a scenerio,

  1. When some side effect needs for one and some needs for other. Then it's important 
  2. To segregate functions among component

Example code view of multiple useEffect() - 

// Effect Hook 1
useEffect(() => {
   // Do your first time logic to get api data
}, []);


// Effect Hook 2
useEffect(() => {
   // Do your logic for only when loggedIn and loggedInMessage changes
}, [loggedIn, loggedInMessage]);

 

How and When needs to clean up useEffect Hook:

When, component would be unmounted, it's need to clean up something. Then we should do that inside useEffect with a return(); 

 

Example 1 of Cleanup useEffect:

  1. API Subscribe inside useEffect()
  2. Remove subscribe functionality after return

 

Example 2 of Cleanup useEffect:

  1. Event listener start on change something.
  2. Need to remove or stop event listener when component deleted.

Example code view -

const [count, setCount] = useState(window.innerWidth);
    
    const calculateWindowSize = () => {
        setCount(window.innerWidth)
    }
    
    useEffect(() => {
      window.addEventListener('resize', calculateWindowSize);

      return () => {
        window.removeEventListener('resize', calculateWindowSize);
      }
}, []);

 

Download Source Code From Github - https://github.com/ManiruzzamanAkash/ReactBasic2Pro/tree/day22

 

 

Previous
#5 Laravel Views
Next
React Context API - An Advanced Introduction and Complete Examples