Next.js Discord

Discord Forum

calling setState in useEffect does not change state

Unanswered
Painted Redstart posted this in #help-forum
Open in Discord
Painted RedstartOP
i'm having trouble setting an initial value to a useState variable in useEffect from localStorage, i use the associated setter and yet setDisplayA( value ) never changes the value of displayA, what am i doing wrong?
    const [displayA, setDisplayA] = useState(undefined)
    //on mount
    useEffect( () => {
        const value = window.localStorage.getItem("stateSwapVisibilityButton") === "true"
        setDisplayA( value )
        console.log("should be true, never is:", displayA === value)
    }, [])

=> should be true, never is: false
i understand this is more of a react question than a next question but im too tired to go in the proper forums :P

1 Reply

Catla
If you console log it after the useEffect it should show correctly. The reason being is that when you use setDisplayA( value ) and then console.log it out after displayA is still set to the initial value. You need to check it after.