Cheatsheets / Learn Redux
Core Redux API
Installing Redux
The redux package is added to a project by first
installing it with npm . npm install redux
Some of the resources imported from redux are:
createStore
combineReducers
Create the Redux Store
The createStore() helper function creates and returns
a Redux store object that holds and manages the const initialState = 0;
complete state tree of your app. The only required const countUpReducer = (
argument is a reducer function, which is called every state = initialState,
time an action is dispatched. action
The store object returned has three key methods that
) => {
ensure that all interactions with the application state
switch (action.type) {
are executed through the store :
case 'increment':
store.getState() return state += 1;
default:
store.dispatch(action)
return state;
store.subscribe(listener)
}};
const store
= createStore(countUpReducer);
The getState() Method
The getState() method of a Redux store returns the
current state tree of your application. It is equal to the const initialState = 0;
last value returned by the store ‘s reducer. const countUpReducer = (
state = initialState,
In the one-way data flow model (store → view →
action
action → store), getState is the only way for the
) => {
view to access the store’s state.
switch (action.type) {
The state value returned by getState() should case 'increment':
not be modified directly.
return state += 1;
default:
return state;
}};
const store
= createStore(countUpReducer);
console.log(store.getState());
// Output: 0
The dispatch() Method
The dispatch(action) method of a Redux store is the
only way to trigger a state change. It accepts a single const initialState = 0;
argument, action , which must be an object with a const countUpReducer = (
type property describing the change to be made. The state = initialState,
action object may also contain additional data to pass action
to the reducer, conventionally stored in a property
) => {
called payload .
switch (action.type) {
Upon receiving the action object via dispatch() , the
case 'increment':
store’s reducer function will be called with the current
return state += 1;
value of getState() and the action object.
case 'incrementBy':
return state += action.payload;
default:
return state;
}};
const store
= createStore(countUpReducer);
store.dispatch({ type: 'increment' });
// state is now 1.
store.dispatch({ type: 'incrementBy'
payload: 3 });
// state is now 4.
The subscribe() Method
The subscribe(listener) method of a Redux store
adds a callback function to a list of callbacks const printCurrentState = () => {
maintained by the store . When the store ‘s state const state = store.getState()
changes, all of the listener callbacks are executed. A console.log(`state: ${state}`);
function that unsubscribes the provided callback is }
returned from subscribe(listener) .
Often, store.getState() is called inside the subscribed
store.subscribe(printCurrentState);
callback to read the current state tree.
Action Creators
An action creator is a function that returns an action,
an object with a type property and an optional // Creates an action with no payload.
payload property. They help ensure consistency and const clearTodos = () => {
readability when supplying an action object to return { type: 'clearTodos' };
store.dispatch() , particularly when a payload is }
included.
store.dispatch(clearTodos());
// Creates an action with a payload.
const addTodo = todo => {
return {
type: 'addTodo',
payload: {
text: todo
completed: false
}
}
};
store.dispatch(addTodo('Sleep'));
Slices
A slice is the portion of Redux code that relates to a
specific set of data and actions within the store ‘s /*
state. This state has two slices:
A slice reducer is the reducer responsible for handling 1) state.todos
actions and updating the data for a given slice. This 2) state.filter
allows for smaller reducer functions that focus on a
*/
slice of state.
const state = {
Often, the actions and reducers that correspond to the
todos: [
same slice of the state are grouped together into a
{
single file.
text: 'Learn React',
completed: true
},
{
text: 'Learn Redux',
completed: false
},
],
filter: 'SHOW_COMPLETED'
}
/*
This slice reducer handles only
the state.todos slice of state.
*/
const initialTodosState = [];
const todosReducers = (
state=initialTodosState,
action
) => {
switch (action.type) {
case 'todos/clearTodos':
return [];
case 'todos/addTodo':
return [...state, action.payload];
default:
return state;
}};
The combineReducers() Function
The combineReducers() helper function accepts an
object of slice reducers and returns a single “root” const rootReducer = combineReducers({
reducer. The keys of the input object become the todos: todosReducer,
names of the slices of the state and the values are filter: filterReducer
the associated slice reducers. })
The returned root reducer can be used to create the
store and, when executed, delegates actions and the
appropriate slices of state to the slice reducers and
then recombines their results into the next state
object.
Introduction To Redux
A React application can share multiple points of data
across components. In many cases managing the data
shared can become a complex task.
Redux is a library for managing and updating application
state. It provides a centralized “store” for state that is
shared across your entire application, with rules
ensuring that the state can only be updated in a
predictable fashion using events called “actions”.
Redux works well with applications that have a large
amount of global state that is accessed by many of
the application’s components. The goal of Redux is to
provide scaleable and predictable state management.
Store
In Redux, a store is a container that holds and manages
your application’s global state.
The store is the center of every Redux application. It
has the ability to update the global state and subscribes
elements of an application’s UI to changes in the state.
Accessing the state should never be done directly and
is achieved through functions provided by the store .
Actions
In Redux, an action is a plain JavaScript object that
represents an intention to change the store’s state. /*
Action objects must have a type property with a user- Basic action object for a shopping list
defined string value that describes the action being that removes all items from the list
taken. */
Optional properties can be added to the action object.
const clearItems = {
One common property added is conventionally called
type: 'shopping/clear'
payload , which is used to supply data necessary to
}
perform the desired action.
/*
Action object for a shopping list
that adds an item to the list
*/
const addItem = {
type: 'shopping/addItem',
payload: 'Chocolate Cake'
}
Reducers
A reducer (also called a reducing function) is a plain
JavaScript function that accepts the store’s current /*
state and an action and returns the new state . A reducer function that handles
Reducers calculate the new state based on the action 2 actions
it receives. Reducers are the only way the store’s or returns the current state as
current state can be changed within a Redux
a default
application. They are an important part of Redux’s one-
*/
way data flow model.
const shoppingReducer = (
state = [],
action
) => {
switch (action.type) {
case "shopping/clear":
return [];
case "shopping/addItem":
return [
...state,
action.payload];
default:
/*
If the reducer doesn't care
about this action type, return
the existing state unchanged
*/
return state;
}
}