This is a short blog post explaining a revelation I had with useEffect
in React, that has probably been causing me problems for a while, since I did not know why my component was not reading the updated props
.
Why won’t my component register the changed values of props
???
The answer for me was that I was not passing in props
to useEffect
as a dependency. It didn’t even occur to me that it was useEffect
which was causing the problem. In many cases, I use useEffect
like componentDidMount
. However, I only want it to run once, because I need to update state, and if useEffect
runs on each state update it will cause an infinite loop. So I pass in an empty array as an argument, to make it run only once:
useEffect(() => {
let d = new Date();
setDate(d);
checkExistingData(d);
}, []);
// <--passed in empty argument
However useEffect
‘s argument decides which variables useEffect
will check to see if they changed. If the array argument is empty, useEffect
will not check any variables for updates, and it will run once and only once. This was a problem for me, since I was using a function that was dependent on the props
of the component. I thought I wanted useEffect
to only run once, but what I really wanted was for it to only run when certain variables were updated. Namely, the props
for my component.
In order to update useEffect
when props
updated, I passed in props
as an argument:
useEffect(() => {
let d = new Date();
setDate(d);
checkExistingData(d);
}, [props]);
// <--'props' passed in
The issue was hard to figure out because other updates to the component made it feel like the component was updating because props
changed. For example, when I made an asynchronous Axios request to my server, there would be a delay before a response was received. When the Axios data was fetched, the component updated: but it wasn’t props that had changed in this case. This deluded me because it seemed like the component was updating because props
was changing, but really the Axios request did not affect props
at all, only local state.
In any case, I’m glad I now know what was preventing my component from updating.
Car stuck by Audrey Odom on Unsplash