14
React Hooks : Demystifying the useEffect hook in under 15 minutes [examples + video]
Hey everyone 👋🏻,
In this article, let us understand about the useEffect React Hook in under 15 minutes.
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;
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;
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;
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
14