DEV Community

Discussion on: React Hooks cheat sheet

Collapse
 
guico33 profile image
guico33
const App = () => {
    const [carSpeed, updateCarSpeed] = useState(10);
    return (
        <div>
            <p>Car is going {carSpeed} km/h</p>
            <button onClick={() => updateCarSpeed(carSpeed + 5)}>
                Speed up
            </button>
        </div>
    );
};

Enter fullscreen mode Exit fullscreen mode

Every time the next state is based on the existing one, better use the callback version of the state updater. Here it would be updateCarSpeed(prevCarSpeed => prevCarSpeed + 5).

Collapse
 
jurajuki profile image
Juraj Pavlović

I will be glad to use the callback version. Thank you for the advice. Do you mind explaining in more detail, why exactly is it better to use the callback version?

Collapse
 
maciekgrzybek profile image
Maciek Grzybek

I think it's similar to setState in the class components - you can be sure that you're updating the correct value, am I right @guico33 ?

Thread Thread
 
wilomgfx profile image
William Cantin

Yes