Epic React V2

Action Function

(See readme.mdx)

It is important if you have a promise async that awaiting for the state, you can get the current state.

The reason this is actually really valuable is because if we were to put this setState call inside of a promise then handler, or after an await, then it will have previously state.

If your state change depends on the current state, then you should use the function callback form like this, which we have in our useState hook also supports a callback like this

Counter:

0

TEST 2 EXAMPLES: Why Action Function currentState?

1. This has a setTimeout 500ms, so to test it click many times

With the currentState (It knows how many times you clicked on it)

Without the currentState, only normal state (It goes one by one, no matter how many times you clicked on it)

2. Another reason is if you call the function multiple times

Example 3 times declared setState in the function

With the currentState (It goes 3 by 3 beacuse currentState)

Without the currentState, It goes one by one, and the fuction is being declared 3 times

So for these two reasons, if your state depends on previous versions of the state, then you should definitely be using the callback form (currentState).

That is why it was important that we update our reducer to support in action(dispatch): function or state.

...(typeof action === 'function' ? action(state) : action)