Home > Software engineering >  How does react`s useEffect hook handle value changes?
How does react`s useEffect hook handle value changes?

Time:01-08

I have a state value

const [fromAirport, setFromAirport] = useState<Airport | null>(null);

and I also have a custom hook that logs out the value of the passed-in argument each time its value changes as below

export const useUpdateLogger = (value: any) => {
  useEffect(() => {
    console.log(value);
  }, [value]);
};

I then use it like this useUpdateLogger(fromAirport);.

Question: The default value of my state variable is null. So why does the value null get logged out yet the variable has not changed? As in it's just null so why are we logging out null and I haven't changed the variable`s variable to anything else? Please explain.

CodePudding user response:

The reason is, useEffect is being executed when the component loads for the first time.

i.e The useEffect with an empty array as a second argument will be called on component mount and component unmount.

For example:

useEffect( () => {
    console.log("mounts");

    return () => console.log("unmounts");
 , []}

when the second argument is not empty then, useEffect will be called, once when the component mounts, it will be called every time when the variable's value is changed, and at last, when the component unmounts

PS: The variable inside the second argument should be passed inside an array and should be a state or a prop which is a state variable somewhere in the parent component.

For example:

const [variable, setVariable] = useState(0);

useEffect( () => {
    console.log("every time the value of variable is changed or when the component mounts");

    return () => console.log("unmounts");
 , [variable]}
  • Related