This article was originally published at codebushi.com
We dive into React's useReducer hook and see how we can use it to manage complex state. We first compare useState and useReducer and slowly add on to our reducer function to make it more flexible.
Key Takeaways From The Video:
2:50 - Implement a counter with useReducer. Looking at how useReducer is similar to useState. Both hooks return an array with two items, the state and a function to change the state.
3:55 - useReducer takes a reducer function as its first argument. Inside the reducer function, you have access to the state.
4:55 - Calling the dispatch() function fires off the reducer function. You need to return the state when you run the reducer function.
7:50 - We can pass additional information into the dispatch(), which will provide additional instructions to our reducer function. We can add if statements inside our reducer function to handle these instructions.
9:50 - Making our initial state an object allows us the state to be more complex. We can have a count and anything else we can thing of, such as a title, in our initial state.
12:30 - Adding an input box allows us to change the title, you would add an onChange to the input and fire off dispatch().
14:20 - To provide even more instructions, we can pass in an action.type to our reducer function. The reducer function will only ever have two arguments, so having our "action" as an object allows us to pass in more information.
20:15 - Instead of many if statements, we can use a switch statement in the reducer function.
23:00 - You can make the action.type ALL_CAPS. This is optional but I find it makes it easier to spot the dispatch functions.
24:00 - In the reducer function, state will first be the initial state, and then it will be the previous state. I like useReducer because you can package all the state and the logic nicely in one spot. All you need to worry about is the one dispatch() and passing that around.
26:40 - When fetching data, we fire off the dispatch() after our data is done fetching. You pass the data through the dispatch action and you set it with the reducer function.
29:40 - We can see the state changing before and after our useEffect is triggered, which fires off the fetch and then the dispatch().
32:00 - Since we have access to all of our state values in the reducer function, we can just alter them directly. We don't always need to pass additional information in with the action.type.
33:40 - The reducer is just a function! You can get creative to make it re-useable. Here is a post I made about Higher Order Reducers: https://codebushi.com/react-hooks-higher-order-reducers/
Redux also has many articles on how to extend the reducer function: https://redux.js.org/recipes/structuring-reducers/structuring-reducers
Finished Code: https://github.com/codebushi/react-useReducer
If you like the YouTube content, please support it by subscribing to the channel!