reactjs(useEffect Hook)

useEffect Hook

useEffect(() => { // write code here });

The useEffect hook is used with react Function components, it provides us the ability to add various features to our react application as mentioned below.

1- The useEffect hook executes after the component rendering is done.

2- If provided no dependency then it will get executed each time component rendering/rerendering happens.

3- If we want it to restrict its execution other then the initial render ,then we need to pass the dependency as a second parameter as shown in below code , so only when the dependency changes then only its gets executed.

useEffect(() => { write code here }, [dependecy]); // Only re-run the effect if dependecychanges

4- continuing the above point if we want useEffect hook to get executed only in the initial rendering and then never run again then pass empty array as a second parameter(below is the sample code syntax).

useEffect(() => { write code here }, []); // Only runs the effect on initial render

5- If we want to run any clean-up code before the components gets destroyed then we can pass it inside a function and return it from UseEffect hook, the clean up code can be unsubscribing any observable, or removing any event listeners added(below is the sample code syntax).

useEffect(() => {

//code line1

return () => {

// add the clean up code here

}

}, []); // clean up code syntax