DEV Community

loading...

React Hooks : Demystifying the useEffect hook in under 15 minutes [examples + video]

The Nerdy Dev
Building products is my profession, Creating content is my passion. We believe that Education should be freely accessible to everyone and no one should be deprived of it.
・2 min read

Hey everyone πŸ‘‹πŸ»,

In this article, let us understand about the useEffect React Hook in under 15 minutes.

Example 1: Counter Example for useEffect

CODE :


import { useState, useEffect} from "react"; 

const Effect = props => { 
  const [counter, setCounter] = useState(0);
  useEffect(() => { 
    console.log('In Effect.js, [AFTER RENDER]');
  }); 
  return ( 
    <div>
      <button onClick={() => setCounter(prevCounter => prevCounter + 1)}>Increment Counter</button>
      <h1>Current Value : {counter}</h1>
      <button onClick={() => setCounter(prevCounter => prevCounter - 1)}>Decrement Counter</button>
    </div>
  )
}

export default Effect; 
Enter fullscreen mode Exit fullscreen mode

Example 2: API Call Side Effect example (useEffect)

CODE :

import { useState, useEffect } from "react"; 

const APICallEffect = props => { 
  const [todo, setTodo] = useState(null); 
  const [id, setId] = useState(1); 
  const fetchTodo = (id) => { 
    return fetch('https://jsonplaceholder.typicode.com/todos/' + id)
    .then(response => response.json()); 
  }
  useEffect(() => { 
    console.log('Effect ran...');
    fetchTodo(id)
     .then(setTodo); 
  },[id]);

  const incrementId = () => setId(prevId => prevId + 1); 

  if(todo === null) return <h1>Loading...</h1>
  return ( 
     <div>
        <h1>id : {id}, todo : {todo.title}</h1>
        <button onClick={incrementId}>incrementId</button>
     </div>
  )
}
export default APICallEffect;
Enter fullscreen mode Exit fullscreen mode

Example 3: useEffect with cleanup

CODE :

import { useState, useEffect, Fragment  } from "react"; 

const EffectWithCleanup = props => { 
  const[xCoordinate, setXCoordinate] = useState(0); 
  const[yCoordinate, setYCoordinate] = useState(0); 
  const handleCoordinateUpdate = event => { 
    console.log(event.clientX, event.clientY); 
    setXCoordinate(event.clientX); 
    setYCoordinate(event.clientY); 
  }

  useEffect(() => { 
    console.log('useEffect ran...'); 
    window.addEventListener('mousemove', handleCoordinateUpdate); 
    return () => {
      console.log('cleanup....');
      window.removeEventListener('mousemove',handleCoordinateUpdate);
    }
  },[]);
  return ( 
    <Fragment> 
      <div>
      <h1>X coordinate: {xCoordinate}</h1>
      <h1>Y coordinate: {yCoordinate} </h1>
      </div>
    </Fragment>
  )
}
export default EffectWithCleanup;

Enter fullscreen mode Exit fullscreen mode

Video πŸ“Ή

So this was it for this one.

If you are looking to learn Web Development, I have curated a FREE course for you on my YouTube Channel, check the below article :

Spare 2 Hours ? If so, utilize them by creating these 10 JavaScript Projects in under 2 Hours

πŸ‘‰πŸ» Follow me on Twitter : https://twitter.com/The_Nerdy_Dev

πŸ‘‰πŸ» Check out my YouTube Channel : https://youtube.com/thenerdydev

Discussion (0)