UseEffect in ReactJs
Hi Everyone! Today we will be learning about useEffect hook in ReactJs which will provide you some clarity with this. It can be a little difficult at first but i will try to explain it in simple language for easy understanding
Through useEffect hook we can do things after rendering. Few examples can be fetching data from API,timers, updating the DOM etc
In Reactjs we can perform side effects using useEffect hook.
A side effect is anything that affects something outside the scope of the current function.
Fetching data from an API
Updating the document title
These are few examples of side effects
The useEffect hook runs after the component has rendered.
useEffect(() => {
// side effect code here
}, [dependencyArray);
import React, { useState, useEffect } from 'react';
function App() { const [count, setCount] = useState(0);
useEffect(() => {
console.log("Component rendered or updated!");
});
return ( <button onClick={() => setCount(count + 1)}> Clicked {count} times ); }
Here in the above code dependency array is not passed so it will run after every render
useEffect(() => {
console.log("Count changed:", count);
}, [count]);
Here it will run everytime the value of count variable changes
useEffect(() => {
console.log("Component mounted!");
}, []);
Here we are passing an empty array so it will run only once
Some common examples of using useEffect are
Fetching data from an API when a component mounts
Listening to window resize or scroll events
Setting the page title dynamically
Hope you all gained some clarity in using useEffect hooks in ReactJs!!