Facebook Pixel

Should I pass a value or a function to useState?

Pass a value for simple initial state. For expensive initial computations, pass a function that returns the value so it only runs once on the first render instead of on every render.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Common useState Mistakes That Break Your React App

Usually because you mutated the state variable directly or mutated an object in place instead of creating a new one. React compares references, so always use the setter and replace objects and arrays with new copies.

Because state updates are batched and count is the same stale value for both calls. Use setCount(prev => prev + 1) so each update receives the correct previous value, even when batched together.

Because React tracks hooks by the order they are called. If a hook is inside a condition, the order can change between renders, which breaks React's internal tracking and causes bugs. Always call hooks at the top level.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.