References
Introduction to Redux
Redux is a small-ish library that takes its design inspiration from the Flux pattern, but is not itself a pure flux implementation. Unlike Flux it doesn't use a dispatcher.
Redux is a library for managing global application state.
The state describes the condition of the application at a given time.
This state is updated frequently over time.
The logic to update the state maybe complex.
The application is medium or large projects.
- Store - read-only state
- Reducers -
- Reducers are functions that calculate a new state value based on previous state + an action
- Create action creators
- actions
- -Actions are plain objects with a {Type:WhateverAction, Data: {someday}}
- Middleware - can manipulate actions as we receive them
- Tie the store to our React views
Redux is a one-way data flow application structure
The UI dispatches an action
=> The store runs the reducers, and the state is updated based on what occurred
=>The store notifies the UI that the state has changed
=> UI re-renders the new state
Principles
- Single source of truth
- The store is immutable
- Updates are made in the reducers by pure functions
Redux Toolkit includes these APIs:
configureStore(): wraps createStore to provide simplified configuration options and good defaults. It can automatically combine your slice reducers, adds whatever Redux middleware you supply, includes redux-thunk by default, and enables use of the Redux DevTools Extension.
createReducer(): that lets you supply a lookup table of action types to case reducer functions, rather than writing switch statements. In addition, it automatically uses the immer library to let you write simpler immutable updates with normal mutative code, like state.todos[3].completed = true.
createAction(): generates an action creator function for the given action type string. The function itself has toString() defined, so that it can be used in place of the type constant.
createSlice(): accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.
createAsyncThunk: accepts an action type string and a function that returns a promise, and generates a thunk that dispatches pending/fulfilled/rejected action types based on that promise
createEntityAdapter: generates a set of reusable reducers and selectors to manage normalized data in the store
The createSelector utility from the Reselect library, re-exported for ease of use.
RTK Query
RTK Query is provided as an optional addon within the @reduxjs/toolkit
package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer for your app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.