Summary

We started the chapter by introducing ourselves to Redux, learning the principles and key concepts. We learned that the state is stored in a single object and changed by pure functions called reducers when actions are dispatched.

We created our own store in our React shop to put the theory into practice. Here are some key points we learned in our implementation:

  • Enumerations for action types give us nice IntelliSense when referencing them.
  • Using interfaces to define the actions gives a nice level of type safety and allows us to create a union type that a reducer can use for the actions it has to deal with.
  • Using read-only properties within the state interface helps us avoid mutating the state directly.
  • Synchronous action creators simply return the required action object.
  • Asynchronous action creators return a function that eventually returns the action object.
  • The reducer contains a branch of logic for each action type it deals with, creating new state by spreading old state into a new object and then overwriting it with changed properties.
  • A function called createStore from Redux creates the actual store. We pass all our reducers merged together along with Redux Thunk middleware to manage asynchronous actions.

We then connected some components to the store. Here are the key points in this process:

  • A Provider component from React Redux needs to sit above all the components that want to consume the store. This takes in a prop that contains the store.
  • A connect HOC from React Redux then wires up the individual components to the store. This takes in two parameters than can be used to map the state and action creators to the component props.

There are lots of bits and pieces to get our heads around when implementing Redux within our React apps. It does shine in scenarios where the state management is complex because Redux forces us to break the logic up into separate pieces that are easy to understand and maintain. 

We learned that we can use a Redux-like approach within just a single component by leveraging React's useReducer function. This can be used when the state is complex and just exists in a single component. 

One task that Redux actions often do is interact with a REST API. We are going to learn how we can interact with REST APIs in both class- and function-based components in the next chapter. We'll also learn about a native function we use to call to a REST API as well as a popular open source library.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.116.20