Mastering React State Management with Redux
- 6.5 hours on-demand video
- 1 downloadable resource
- Full lifetime access
- Access on mobile and TV
- Certificate of Completion
Get your team access to 4,000+ top Udemy courses anytime, anywhere.Try Udemy for Business
- Learn to create a React app with webpack and securing API authentication.
- Learn how to maintain a session on the client.
- Learn how to avoid scaling problem by using a higher-level too.
- Enhance your application store with Redux's advanced API.
- Avoid the scaling problem by using a higher-level tool.
- Learn to tackle and avoid common performance pitfalls.
One chief disadvantage to single page apps is that they’re less accessible to search engines. Using isomorphic rendering gives you full searchability and a performance boost as well.
Reorganize your client code for universal access
Compute the virtual DOM on the server before the client loads
Make sure you’re really rendering the same DOM in both places!
When state management becomes complex, it becomes less practical for components to handle it. Redux offers a testable and predictable implementation of the FLUX pattern.
Move state management code into actions and reducers
Initialize the Redux store with your reducers
Use react-Redux to bind the Redux store to your view layer
We need to ensure consistency between the client and the server side rendering code when computing the virtual DOM. When adding Redux to the mix, this includes keeping the application state consistent as well.
Hookup Redux on the server and force a checksum warning
The client then creates the store using the preloaded state from the previous step
An API without data is like a restaurant without food. Knex provides a thin wrapper around sql that will get our tables populated in no time.
Install and configure knex for postgresql
Run a migration to create a database table
Execute a seed script to populate the table with records
Sometimes we need to do more than just read or write data. Object relational managers provide higher level abstractions as well as features like model validation and eager loading of associated data.
Observe how plain knex queries are insufficient for eager loading
Download Bookshelf and create models for each database table
Perform an eager loading query
Expanding the auth scheme to accept cookies can make it easier for browser based clients to stay logged in, but it introduced a CSRF risk that must be protected against.
Allow token to be written to and read from an http-only cookie
Add CSRF tokens to prevent forged HTTP requests
Enable CORS to accept AJAX requests from specified origins
Deciding which screen to show based on application state is a problem for everyone. We need a client side router to map URL’s to our different screens.
Use react-router redirects to switch between home and login screen
Add new routes and pages to the application
Build a nav menu so users can get to any screen
Anything we introduce on the client must also work with SSR. We can accomplish this by using the static router.
Add new middleware to log all server requests
Hookup static router on the server to get routes working with SSR
Use static routing context to add status codes to server responses
Client side validation can enhance the user experience by preventing most invalid data from getting to the server.
Integrate Redux-form into the Redux application
Add validation and write custom Redux-form components
Write the code needed to submit the form data to the server
All applicable validation checks should be run on the server, without exception. Validating the submission on the client should not be considered sufficient.
Add synchronous validation checks to the model to validate formats
Add asynchronous validation checks to compare values with the database
Integrate the backend errors into the UI
CRUD applications typically contain list views for the resources being managed. Use Redux and react to retrieve, store, and display data in a table to be browsed.
Expose and endpoint to return a single page of customer data
Write the Redux code to retrieve and store the data
Write components to display the customers in a data table
An API should limit the number of records it returns to prevent performance problems. Flipping through pages of list data is a common interface for browsing records from the API.
Split the display code into smart containers and presentational components
Add the Redux code needed to page through the API data
Write UI pagination controls that execute the paging
Similar Redux logic must often be applied in multiple places. Avoid repetition by learning how to safely reuse actions and reducers.
Build action factories to dynamically generate actions for the right reducer
Create higher order reducers to listen for actions from the right factory
Rework components to communicate with higher order modules
To really get the most out of server side rendering, the data your page needs can be loaded before the client renders.
Make preloading easy by keeping application logic in reusable places
Allow for links to a specific page in your table by using the query
Design a solution to be used across multiple resources
As an application evolves, we need to maintain confidence that our code does what we think it does. Writing unit tests for the most complex parts of an application is essential to ensuring long term quality.
Install utilities required for running tests, making assertions, and mocking
Write simple tests against pure, functional reducers
Mock HTTP calls to test success and failure scenariosof asynchronous action creators
Use prop-types to generate runtime warnings for component type mismatches
Explore linting and auto-formatting to help ensure consistency of coding style
This video aims to explain the different types of state that can exist in a Redux application and tries to solve the way we consume state in components by introducing the presentational/container component pattern.
Identify and separate What's Global State and What's Local State
Divide your components into Presentational and Container Components
Connect your Container Components with the Global Store to consume Global State
This video aims to explain how to structure your Global State store. Provides some ways to distinguish what's a data model and what's feature/UI state.
Identify your application's models
Identify your application's feature state and which models it needs
Derive model data to feature state and identify features that act as models
This video aims to explain the two most common ways to structure a project and show its advantages and disadvantages.
Think about your project constraints and future concerns
Choose the project structure that suits your needs – structure by role or by domain
Introduce necessary changes to adapt the project structure to your current project
This video aims to explain a new project structure build specifically for working with Redux application. The concept of Redux ducks will be introduced and with it the main tips and advantages it brings.
Identify which models exist in your application
Create a file for each model and follow the Redux ducks convention
If the project keeps growing consider changing to a folder structure such as re-ducks
This video aims to explain the concept of state, state management, and how to handle user events. It demonstrates why using an MVC architecture to manage user events can become unmanageable.
Identify which state needs to be shared across components
Trigger an update from one component and listen to it from another
Update a component state with the event that other component dispatched, add a check to avoid infinite update loops
This video aims to explain the concept of data entry points and functional programming side effects. It demonstrates why using an MVC architecture to manage API data can become unmanageable.
Identify which components share API data
Trigger an update from one component when receiving new API data, listen to it from another
Update a component state with the event that other component dispatched, add a check to avoid infinite update loops
This video aims to explain the concept of two-way data binding and one-way data flow. It demonstrates why, one-way data flow is easier to maintain than publisher/subscribe or two-way data binding.
Identify the main pitfall of the current publisher/subscribe implementation
Create a flux store that hold our state updates logic
Refactor components to use flux instead of pub/sub
This video aims to explain the most common anti-patterns when write action creators. It demonstrates why using an MVC architecture to manage user events can become unmanageable.
Avoid which Gould be split into more explicit things
Avoid having all the business logic inside the action creator
Centralise the side effects in the reducer function
This video aims to explain the available mechanisms for code reusing inside a reducer. It demonstrates the advantages of using composition over action reusing.
Identify the actions that are similar enough to be refactored
Write smaller helper functions to be applied in several actions
Compose one reducer with other smaller reducers
This video aims to explain how we can use React Context API to replace Redux. It shows how we can use the same architecture without Redux dependency.
Create a React component that will hold the state and the methods to update it
Wrap your component tree with the created context provider
Use the context consumer or the class contextType property to read the props
This video aims to explain how to use Redux actions to avoid writing Boilerplate when defining action creators.
Import createAction from Redux actions
Pass the action type constant as parameter to createAction
If you need to pass a custom payload use the payload creator function
This video aims to explain the main disadvantages of using a React router with Redux and propose an alternative that handles routing at a state level.
Define your routes and your store config using redux-first-router
Create a component that makes the routing happen
Write to the URL using Redux actions and read from the URL with Container Components
This video aims to explain how we can improve the performance of our app following some patterns that are easy to apply.
Normalize the structure of your state
Connect the items of a list, instead the list itself
Prefer having many connected components to having a few that pass many props down
This video aims to explain the concept of state Selectors and how to use them to avoid performing unnecessary expensive calculations.
Define pure functions that select a slice of your state
Use reselect's createSelector to memoize the expensive derived state calculations
Use your Selectors in mapStateToProps method
This video aims to explain the concept of windowing or using virtualised lists.
Identify a list of elements that can be expensive to render
Define your list container using a solution such as react-window
Map all elements of the list inside the virtualized container, render only the ones visible
This video aims to explain how to code-split your application's components and reducers.
Code split components by page using the dynamic import syntax.
Create a reducer registry that handles the reducer's dynamic assignment to the store
Call the registry's register method inside each redux duck, to register it when the duck gets imported
This video aims to explain what is middleware in the context of Redux and how can we build one.
Write a middleware function that receives the store and that returns a function that receives the next middleware and that in turn returns a function that receives an action
Use applyMiddleware to build your middleware chain
Pass your middleware chain as a store enhancer intro the createStore function
This video aims to explain how Redux-thunk middleware works, and how to create a thunk action creator.
The middleware checks if the dispatched action is a function
If it's a function, it unwraps it passing getState and dispatch as arguments
To create a thunk, you just need to dispatch a function that receives dispatch as argument, and calls it afterwards
This video aims to explain the concept of store enhancers, covering the Redux enhancer’s signature and how to add them to our application using compose.
Create a store enhancer by passing a store creator function and returning an enhanced version of that store creato.
Add a store enhancer to your application by passing it as the last argument of the createStore function
Add several store enhancers to your application by using the compose function to merge them into a single enhancer
This video aims to explain how to build a custom store enhancer. As an example, we'll build an enhancer that saves the state to local storage.
Build read/write methods to save state to local storage
Create store enhancer that instantiates the store and wraps dispatch
Use dispatch wrapper to serialize state after each dispatched action
This video aims to explain the most common Redux-Thunk anti-patterns and how to avoid them.
Consolidate all dispatches you can into a single action dispatch
Avoid inconsistent state by treating dependent updates as a single update
Move all data manipulation logic inside the reducer
This video aims to explain the purpose behind Redux-Pack library, and how to use it. We'll discuss the main difference between Redux-Pack and Redux-Thunk and the trade-offs among them.
Update action creators to return a promise instead of a function
Use the handlePack function to handle each one of the Redux-Pack lifecycle steps on the reducer
Chain promises to handle dependent requests inside a single promise
This video aims to explain what is Redux-Saga, how to create a saga and how to test it.
Include the saga middleware, import the root saga and call run
Within a specific saga, listen to an action type and react accordingly
Test your sagas by comparing the output of each one of the generator's steps
This video aims to explain what are the necessary steps to get a React app rendering from the server side.
Extract your store and app init into functions you can reuse across server and client side
Instantiate the store and the application passing the request pathname as initial route
Render your app to string using react dom and render it as HTML
This video aims to explain how to rehydrate your react app on the client side, providing a single page application experience.
Prepare an application bundle for the client
Server render your Redux state into a global variable and read it on the client
Call react hydrate to add event listeners
This video aims to explain the concept of fetching data before server rendering your app, and how to do it using Redux-first-router.
Declare your data dependencies at a route/page level
Await for the data fetching to resolve before server rendering the app
Wrap our action creators with a promise so we can await for them
This video aims to explain what it would take for us to remove the data from Redux and use an external cache to render it.
Remove the data key and data specific logic from all of the state reducers
Create a cache instance that saves all API data in memory
Read from the cache at the containers level to pass data into components
This video aims to explain the main issues from our previous attempt to use a cache when server rendering. Propose a solution that will work for both client and server rendering.
Create cache instance on every server request. Pass it down the app using React context
Use higher order component to read cache from context
Use Redux-Thunk extra argument to read the cache when using thunks
This video aims to explain how to persist your cache layer using IndexedDB. And discuss what are the tradeoffs of using redux without data. In the end we will propose alternative solutions.
Persist your cache data on IndexedDB every time the cache is updated
Restore your data in memory cache on app startup
Consider more robust alternatives such as GraphQL
- Familiarity with data binding on the front end and object-relational management on the back end are strongly recommended.
Redux completes the missing piece of the React framework and is used at the core of React for most complex React projects. It brings a clean and testable design to the table using a purely functional approach and provides a solid, stable, and mature solution to managing state in your React application.
With this master class course, you will start with building a minimal web pack application & quickly transforming it into an isomorphic application with full API integration, including secure authentication & maintaining a session on the client. Then you'll dive into common performance pitfalls and how to avoid them using various tools that interact with Redux. Moving further you will also be learning how to combine React Router with Redux and make your apps more data-driven and real-time.
By the end of this course, you will be master making better architectural decisions and learn to tackle any performance pitfalls. Also, gain in-depth knowledge to test every aspect of your client’s application & built real-time & data-driven applications.
Contents and Overview
This training program includes 2 complete courses, carefully chosen to give you the most comprehensive training possible.
The first course, Redux – End to End you'll start with building an app piece by piece, starting with a minimal web pack application and quickly transforming it into an isomorphic Redux application with full API integration, including secure authentication.
The second course, Mastering Redux empowers Redux users by helping them make better architectural decisions. After going through the architectural standpoint of building a large-scale Redux application, you'll dive into common performance pitfalls and how to avoid them. Next, you'll make tools that interact with Redux. Moreover, you'll go through the different approaches to asynchronous effects and how to maintain an organization at scale. You'll be introduced to the server-rendering concept and learn to deal with it in React applications. Also, you'll understand what's needed to load your Redux store from the server. Finally, we mention use cases where Redux might not be that useful and talk about helpful tools in the react-Redux ecosystem.
About the Authors:
Tiago Garcia calls his relationship with computers and computer science “love at first sight”, which happened when he was only 9. He pursued this passion ever since and finished his Master’s degree in Computer Science in Faculdade de Ciências e Tecnologia - UNL in Lisbon in late 2010. A few months after, he joined Vizzuality as a PHP backend developer. His other passions are gaming and music. Some believe he was born already wearing earphones.