DEV Community

Jayant Khandelwal
Jayant Khandelwal

Posted on • Edited on

6 2

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay