Common useState() Hook Mistakes in Reactjs

Common useState() Hook Mistakes in Reactjs

useCallback Hook returns a memoized callback function.
useCallback Hook only runs when dependencies update.

Incorrect Previous value

When using setState, you can access the previous state as an argument of callback. Here if you click multiple times on delay Increment CTA  state not updated correctly. 

useState hook mistake


How to solve above issue. 

let’s use callback when setting state. remove dependency from use Callback.
Now if you click multiple time on delay Increment CTA , it's update set correctly and you get correct value.


solve useState hook previous value


Forgot to initialize State()

This gives errors during code execution. like “Can’t read properties of undefined”.

Below code if you forgot to give initialize value to count it's give undefined error first, when you click + button it's give NaN.

initialize useState() hooks

How to solve it

Give initialize value to count. Now it's working while you click on + CTA it's give increment value of state.

initialize useState() hooks reactjs

























Previous Post Next Post