Home > other >  Can I access a variable inside useEffect without use useState?
Can I access a variable inside useEffect without use useState?

Time:09-24

I want to access a variable inside useEffect hook without use useState. How can I do that?

Here my codes:

let numberOfLessons;

useEffect(() => {
        getLessons()
            .then(response => 
                numberOfLessons = response.data().length // 6
            })
            .catch(error => {
                console.log(error)
            })
    }, [])


console.log(numberOfLessons) // undefined

CodePudding user response:

There is nothing to physically stop you from doing this. But the downside is that your variable is not part of the React state.

It's value is initially set to undefined. Later on when you set it to 6 that will not trigger React to re-render the view, so your 6 might not ever appear on the screen.

But perhaps that doesn't matter to you. If this variable is only used e.g. for logging then it wouldn't matter if React knows about it or not.


In your exact example console.log is undefined because you are logging before the value is set. This is not really a React specific problem. That's just how async code works. If you did

setTimeout(() => console.log(numberOfLessons), 5000)

then you would get the 6 as expected.

  • Related