useState vs useReducer
We can use the useState
to internally maintain state of a react component but as soon the internal state gets complex the number of useState
can get overwhelming. For this we can use the useReducer
.
useReducer
For the sake of learning middleware to handle async operations the example has been kept simple. The following example is taken from the official react documentation. It has two buttons one is used to increment and other is used to decrement. The application uses useReducer
to maintain its state.
1 | const initialState = { count: 0 }; |
Lets suppose that on the button click we want to call an api, and increment it by the value from returned the api. I know its a superficial example but the point is to demonstrate how to handle async
in useReducer
As we know that reducers are pure function and can not have any side effect so we can not perform the api call inside the useReducer
. To avoid this we can use thunks
Thunk
What is a thunk? thunk is function which is returned by another function. Its more easier to explain it via code:
1 | function notAThunk() { |
Thunk is a piece of code encapsulated inside a function which can be called at a later time.
So instead of passing an object to the dispatch function we will pass a function. This passed function is thunk
, and will be executed at a later time by the middleware
. lets modify our code so it can handle the thunk
via middleware
. Inside Counter we will replace:
1 | const [state, dispatch] = useReducer(reducer, initialState); |
with the following code:
1 | const [state, orignalDispatch] = useReducer(reducer, initialState); |
We have renamed the dispatch
returned by useReducer
to orignalDispatch
. In essence we have created a middleware. As the following code is executed whenever we dispatach an action and before the action is received by the reducer
1 | if (isFunction(action)) { |
We have created a new function called dispatch
. Our implementation first checks if the passed action
is a type of function if it is a function then it is called with orignalDispatch
as a arugment, otherwise we simply pass the action to orignalDispatch
.
Now lets simulate a fake api call:
1 | const asynIncrementApi = () => { |
asynIncrementApi
returns a promise with a value between 1 to 10 after atleast 1000ms
have passed.
With api in place, Lets add a new button Async Increment
to the Counter
.
1 | Count: {state.count} |
Lets hook up Async Increment
with event handler.
1 | <button |
When user clicks on the Async Increment
button, its event handler is executed which makes a call to dispatch function. The action
to dispatch function is our thunk
.
In the above example following function is the thunk
1 | () => { |
Inside the dispatch function our check isFunction
returns true
and executes the thunk
. In this case our thunk
ignores the parameters passed to it. It is because the dispatch
is in our scope but there might be some case where the dispatch
might not be in scope (like if code is outside the component or in a separate file) so its better to pass it.
Inside our thunk
the backend api is called and as soon the promise returned by the api is resolved we dispatch a new action with type of increment_async
and count
with value returned from the backend.
This is all which is required to handle the asyc actions. Now lets update our reducer
to handle the increment_async
.
1 | case "increment_async": |
Below is all the code and here is link to the codesandbox
1 | import "./styles.css"; |
Refactor the middleware into a separate hook
Lets create a new hook which encapsulates the logic of creating reducer and middleware into a separate hook.
1 | const useThunkReducer = (reducer, initialState) => { |
Now we use useThunkReducer
instead of useReducer
. This example was inspired from here.