DEV Community

Jayant Khandelwal
Jayant Khandelwal

Posted on • Edited on

useState Hook as simple as a 'cake'!

"Returns a stateful value and a function to update it."

Note: A state variable can be a number, boolean, variable, object, or even an array

Method 1:
Hooks without functional form

vs

Method 2:
Alt Text

*Always Prefer "Method 2" over "Method 1" *

Reason:
React functional components are just closures, the state value that you have in the closure might be outdated

1.) The update function is considered to be async in nature which means that you shouldn't expect immediate value change for the count after setCount call and, thus can't rely on that new value.

2.) When you call the update function multiple times in the same closure, the react functional component without a functional form might break.

The "+" and "-" buttons use the functional form because the updated value is based on the previous value. But the “Reset” button uses the normal form because it always sets the count back to the initial value.

Happy Coding

-Jayant Khandelwal

Buy Me A Coffee

Top comments (0)