Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React cannot update state quick enough

I think due to React’s useState asynchronous nature, I am running into an issue where when I try to update the state quickly it does not work. I know of course I am doing something wrong, but not sure what. Basically I have a component that when it loads, might fire off a callback in rapid succession, in this case two times. This should update the state of the parent component by appending to the array in the state system. But it fails. I understand why it fails, but not what I am doing wrong.

export const Foo = () => {
    const [selected, setSelected] = React.useState<any[]>([]);

    const onSomeFastAction = (value: any) => {
        console.log(`adding ${value} to selected`)
        console.log(selected) // Prints [] on first AND second logs
        setSelected([...selected, value])
    }

    React.useEffect(() => {
        // Only the second value is ever in the array and this only logs once
        console.log(selected);
    }, [selected])

    return (
        <CrazyFastComponentThing
            onThingThatHappens={onSomeFastAction}
        />
    )
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You must use a function to set newState:

export const Foo = () => {
    const [selected, setSelected] = React.useState<any[]>([]);

    const onSomeFastAction = (value: any) => {
        console.log(`adding ${value} to selected`)
        console.log(selected) // Prints [] on first AND second logs
        setSelected(prevState => {
            const newState = [...prevState];
            newState.push(value);
            return newState;
        }
    }

    React.useEffect(() => {
        // Only the second value is ever in the array and this only logs once
        console.log(selected);
    }, [selected])

    return (
        <CrazyFastComponentThing
            onThingThatHappens={onSomeFastAction}
        />
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading