Reader small image

You're reading from  Learn React Hooks

Product typeBook
Published inOct 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781838641443
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Daniel Bugl
Daniel Bugl
author image
Daniel Bugl

Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.
Read more about Daniel Bugl

Right arrow

Redux and Hooks

In the previous chapter we learned about React class components, and how to migrate from an existing class component-based project to a Hook-based one. Then, we learned about the trade-offs between the two solutions, and we discussed when and how existing projects should be migrated.

In this chapter, we are going to turn the ToDo application that we created in the previous chapter into a Redux application. First, we are going to learn what Redux is, including the three principles of Redux. We are also going to learn when it makes sense to use Redux in an app, and that it is not appropriate for every app. Furthermore, we are going to learn how to handle state with Redux. Afterward, we are going to learn how to use Redux with Hooks, and how to migrate an existing Redux application to Hooks. Finally, we are going to learn the trade-offs of Redux, in order to be able...

Technical requirements

A fairly recent version of Node.js should already be installed (v11.12.0 or higher). The npm package manager for Node.js also needs to be installed.

The code for this chapter can be found on the GitHub repository: https://github.com/PacktPublishing/Learn-React-Hooks/tree/master/Chapter12.

Check out the following video to see the code in action:

http://bit.ly/2Mm9yoC

Please note that it is highly recommended that you write the code on your own. Do not simply run the code examples that have been provided. It is important that write the code yourself in order for you to be able to learn and understand properly. However, if you run into any issues, you can always refer to the code example.

Now, let's get started with the chapter.

What is Redux?

As we have previously learned, there are two kinds of state in an application:

  • Local state: For example, to handle input field data
  • Global state: For example, to store the currently logged-in user

Previously in this book, we handled local state by using a State Hook, and more complex state (often global state) using a Reducer Hook.

Redux is a solution that can be used to handle all kinds of state in React applications. It provides a single state tree object, which contains all application state. This is similar to what we did with the Reducer Hook in our blog application. Traditionally, Redux was also often used to store local state, which makes the state tree very complex.

Redux essentially consists of five elements:

  • Store: Contains state, which is an object that describes the full state of our application—{ todos: [], filter: 'all' }
  • Actions...

Handling state with Redux

State management with Redux is actually really similar to using a Reducer Hook. We first define the state object, then actions, and finally, our reducers. An additional pattern in Redux is to create functions that return action objects, so-called action creators. Furthermore, we need to wrap our whole app with a Provider component, and connect components to the Redux store in order to be able to use Redux state and action creators.

Installing Redux

First of all, we have to install Redux, React Redux, and Redux Thunk. Let us look at what each one does individually:

  • Redux itself just deals with JavaScript objects, so it provides the store, deals with actions and action creators, and handles reducers...

Using Redux with Hooks

After turning our todo application into a Redux-based application, we are now using higher-order components, instead of Hooks, in order to get access to the Redux state and action creators. This is the traditional way to develop a Redux application. However, in the latest versions of Redux, it is possible to use Hooks instead of higher-order components! We are now going to replace the existing connectors with Hooks.

Even with Hooks, the Provider component is still required in order to provide the Redux store to other components. The definition of the store and the provider can stay the same when refactoring from connect() to Hooks.

The latest version of React Redux offers various Hooks as an alternative to the connect() higher-order component. With these Hooks, you can subscribe to the Redux store, and dispatch actions without having to wrap your components...

Migrating a Redux application

In some Redux applications, local state was also stored in the Redux state tree. In others, React class component state was used to store local state. In either case, the way to migrate an existing Redux application is as follows:

  • Replace simple local state, such as input field values, with State Hooks
  • Replace complex local state with Reducer Hooks
  • Keep global state (state that is used across multiple components) in the Redux store

We have already learned how to migrate React class components in the previous chapter. In the previous section, we learned how to migrate from Redux connectors to using Selector and Dispatch Hooks. We are now going to show an example of migrating Redux local state to a Hook-based approach.

Let us assume that our existing todo application stores the input field state in Redux, as follows:

{
"todos": [],
...

Trade-offs of Redux

To wrap up, let us summarize the pros and cons of using Redux in a web application. First, let us start with the positives:

  • Provides a certain project structure that allows us to easily extend and modify code later on
  • Fewer possibilities for errors in our code
  • Better performance than using React Context for state
  • Makes the App component much simpler (offloads state management and action creators to Redux)

Redux is a perfect fit for larger projects that deal with complex state changes, and state that is used across many components.

However, there are also downsides to using Redux:

  • Writing boilerplate code required
  • Project structure becomes more complicated
  • Redux requires a wrapper component (Provider) to connect the app to the store

As a result, Redux should not be used for simple projects. In these cases, a Reducer Hook might be enough. With a Reducer Hook...

Summary

In this chapter we first learned what Redux is, as well as when and why it should be used. Then, we learned about the three principles of Redux. Next, we used Redux in practice to handle state in our ToDo application. We also learned about synchronous and asynchronous action creators. Then, we learned how to use Redux with Hooks, and how to migrate an existing Redux application to a Hook-based solution. Finally, we learned about the trade-offs of using Redux and Reducer Hooks.

In the next and final chapter, we are going to learn about handling state with MobX. We are going to learn what MobX is and how to use it the traditional way with React. Then, we are going to learn how to use MobX with Hooks, and we will also understand how to migrate an existing MobX application to a Hook-based solution.

Questions

In order to recap what we have learned in this chapter, try to answer the following questions:

  1. What kind of state should Redux be used for?
  2. Which elements does Redux consist of?
  3. What are the three principles of Redux?
  4. Why do we define action types?
  5. How can we connect components to Redux?
  6. Which Hooks can we use with Redux?
  7. Why should we create reusable selectors?
  8. How can we migrate a Redux application?
  9. What are the trade-offs of Redux?
  10. When should we use Redux?

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React Hooks
Published in: Oct 2019Publisher: PacktISBN-13: 9781838641443
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Daniel Bugl

Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.
Read more about Daniel Bugl