#javascript#reactjs#beginers
Prerequisite: Knowledge of JavaScript and Basic knowledge of ReactJS.
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.
Our React Application interact with outside world with functions. useEffect is ReactJS Hook which is used to handle side effect functions (side effect function are those function that communicate with outside world or just out of ReactJS ecosystem ) and by using useEffect we can separate them into other function.
useEffect hook must be declared inside the React component at top level of function. it gives several advantages:
*It will have access to those data that is required in useEffect hook.
useEffect(function sideEffect(){
.....
}, [/*array_of_dependency*/])
Every time a React components finish rendering, useEffect run unless you specified dependencies in the dependencies array.
There are several cases where we should consider using useEffect hook. Most import of them are:
import React, { useEffect } from "react";
const UseEffectHookExmaple = () => {
useEffect(() => {
document.title = "UseEffect called when a component Rendered";
});
return (
<div>
<h1>UseEffect Hook Called every time a component is rendered</h1>
</div>
);
};
export default UseEffectHookExmaple;
2. Run once after that if component re-renders, then it will not run.
import React, { useEffect } from "react";
const UseEffectCalledOnce = () => {
useEffect(() => {
document.title = "UseEffect called Once when component Rendered";
}, []);
return (
<div>
<h1>UseEffect called Once when component Rendered</h1>
</div>
);
};
export default UseEffectCalledOnce;
3. Run once by default after that if prop values changes, then run:
import React, { useEffect } from "react";
const UseEffectCalledOnce = ({ PageTitle }) => {
useEffect(() => {
document.title = PageTitle;
}, [PageTitle]);
return (
<div>
<h1>UseEffect called when PageTitle is updated</h1>
</div>
);
};
export default UseEffectCalledOnce;
* If you have any suggestion please let us know in comment section.