It is a react hook that lets you run side-effects in function components.
What are side-effects? A side effect is anything that affects something outside the scope of the function. Examples of side effects are:
setTimeout setInterval.Imagine this example, When you are driving a F1 car, once the car is fueled you dont stop every single lap to refuel right, strategies are made to refuel the car, here Pit Stop is a side-effect and to refuel the car at the pit stop is useEffect. With useState, you do this, but with useEffect this changes.
Let’s convert this example in coding - When data has been fetched once via the server, its not required to fetch it again and again, only when some dependencies change is when the data should be fetched again. This is handled by useEffect.
Here, I have written a Todo useEffectfunction where, every time the todo changes, the useEffect hook is used and re-render takes place. It only renders once. When the todo id is changed is when the re-render takes place again.
function Todo({id}) {
const [todo, setTodo] = useState(null);
useEffect(() => {
if (id) {
axios.get("<http://localhost:3000/todos/>" + id)
.then(function(response) {
setTodo(response.data.User)
});
}
}, [id]);
if (!todo) {
return <div>Loading...</div>;
}
return <div>
<h2>{id}</h2>
<h1>{todo.title}</h1>
<h4>{todo.description}</h4>
</div>
}
In the below example, I am making a scroller when everytime the user scrolls,
window.scrollYThis is a very good example of useEffect of rendering only when change is occurring and here the change is the scroll position.
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0);
useEffect(() => {
const handleScroll = () => {
setScrollY(window.scrollY); // window.scrollY gives the vertical scroll position in pixels
};
window.addEventListener('scroll', handleScroll); // everytime the user scrolls, listen to the rendering component scroll and run this function `handleScroll`
return () => {
window.removeEventListener('scroll', handleScroll); // eveytime user stops scrolling, remove the listener who is listening to the scroll and stop rendering shit.
};
}, []);
return <p>Scroll Y: {scrollY}</p>
}
Another example is to fetch data and only updating the DOM when data query is changed.
function Two({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(res => res.json())
.then(data => setUser(data));
}, [userId]);
return (
<div>
{user ? <p>{user.name}</p> : "Loading..."}
</div>
)
}
Here, the state dependency for the useEffect is userId and when that changes, the DOM changes.