44
loading...
This website collects cookies to deliver better user experience
import React, { useEffect } from "react";
function SimpleUseEffect() {
useEffect(() => {
alert("Component Rendered")
});
return (
<div>
<b>A Simple use of useEffect...</b>
</div>
)
}
Effect: An anonymous callback function that houses your useEffect logic. This logic is executed based upon how you set up useEffect() to run
Dependency array: The second is an array that takes in comma-delimited variables called the dependency list. This is how you change the way useEffect() operates.
useEffect(() => {
// some component logic to execute...
}, []);
/*
Notice the empty array as the second argument above.
We don't pass anything to the array as we don't want useEffect() to depend on anything - thus the purpose of having the dependency list in the first place.
*/
const [value, setValue] = useState(0);
useEffect(() => {
// some component logic to execute...
}, [value, setValue]);
/*
Notice the dependency array as the second argument above.
We pass 'value' to the array as an example to showcase how this hook can work. This useEffect() invocation will execute every single time 'value' is updated.
Another thing to mention is that arguments in the dependency list don't have to come from other hooks like they do in this example - they can be other forms of data that are assigned to a particular variable where the underlying assigned values can be/are mutated.
*/
React.useEffect(
() => {
val.current = props;
},
[props]
);
React.useEffect(() => {
return () => {
console.log(props, val.current);
};