React Hooks are a feature introduced in version 16.8 of React. They allow function components to have access to state and other React features, such as lifecycle methods, without the need for class components.
Today we are seeing about useEffect hook in react.
The useEffect Hook allows you to perform side effects in your components.
Some examples of side effects are: fetching data, directly updating the DOM, and timers.
useEffect accepts two arguments. The second argument is optional.
useEffect(<function>, <dependency>)
<function>
— inside the function we write a callBack function.
<dependency>
— inside the dependency we should give a dependency array.
the below example have contents in app.js
import './App.css';
import { useState, useEffect } from 'react';
function App() {
const [count, setCount] = useState(0);
useEffect(()=>{
// this hook will run at the time when our component mounts.
console.log('the count is',count);
// this is optional return statement, is that what will happen when
// the component unmounts.
return () =>{
console.log('the component was unmounted')
}
// what we are using inside of useEffect we must metion that
// inside of dependency array.
// the code inside the useeffect will execute once, aftee that it
// won't execuded when we forget to give values inside the dependency array
}, [count]);
return (
<div className='App'>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
</div>
);
}
export default App;
Here we should know that how useEffect works, it will execute the code at the component mounts after that at every time we update the values inside the dependency array the component will destroy and rebuild again,
that is the return function inside the useEffect hook will execute at the time.
The output for this above code will be,
you will see the changes in the console by inspecting that webpage
the console will be,
At every time the count value changes the component will destroy and again it would mount in the component tree.
I hope that you will have a better understanding of useEffect, If you have any doubts comment in this post.
Thank you, Have a nice day 💖…….
Top comments (0)