I don't understand why my useEffect()
React function can't access my Component's state variable. I'm trying to create a log when a user abandons creating a listing in our app and navigates to another page. I'm using the useEffect()
return
method of replicating the componentWillUnmount()
lifecycle method. Can you help?
Code Sample
let[progress, setProgress] = React.useState(0)
... user starts building their listing, causing progress to increment ...
console.log(`progress outside useEffect: ${progress}`)
useEffect(() => {
return () => logAbandonListing()
}, [])
const logAbandonListing = () => {
console.log(`progress inside: ${progress}`)
if (progress > 0) {
addToLog(userId)
}
}
Expected Behavior
The code would reach addToLog()
, causing this behavior to be logged.
Observed Behavior
This is what happens when a user types something into their listing, causing progress
to increment, and then leaves the page.
- The
useEffect()
method works perfectly, and fires thelogAbandonListing()
function - The first
console.log()
(aboveuseEffect
) logs something greater than 0 for theprogress
state - The second
console.log()
logs 0 for theprogress
state, disabling the code to returntrue
for theif
statement and reach theaddToLog()
function.
Environment
- Local dev environment of an app built with Next.js running in Firefox 76.0.1
- nextjs v 8.1.0
- react v 16.8.6
I'd really appreciate some help understanding what's going on here. Thanks.