Redux is an open-source js library for handling web application state. This library can be used in different web app frameworks such as React and Angular. The following outlines how to use redux in react web applications.

How to install

There are two ways for adding redux to your project in case you want to initialize a new react app, or add redux to your current react app.

In case you want to create a react app using redux, easily write the following command:

npx create-react-app my-app --template redux

Otherwise, if you prefer to code by TypeScript you can run the below command:

npx create-react-app my-app --template redux-typescript

By running the above codes, it creates a react app integrated with Redux.

Variously, you can install the redux package in your current project by running the following npm command:

npm install redux

or

yarn add redux

In addition, you need to install react-redux and redux-devtools-extension packages as well:

npm install react-redux
npm install redux-devtools-extension

or

yarn add react-redux
yarn add redux-devtools-extension

How to implement

First, you need to create a global store for the app (store.js):

import { applyMiddleware, createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import reducers from './reducers';

const middlewares = [];
const store = createStore(reducers, composeWithDevTools(applyMiddleware(...middlewares)));
export default store;

The above code creates a global store by adding reducers and middleware. In this case for simplicity, the middlewares are empty but you can add router and saga middlewares as examples.

Then, it is needed to be added the store to the app (index.js):

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux';
import store from './store';

ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App/>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);

Reducers are pure functions that take the current state and an action as arguments and return the updated state. The reducers are combined to add to the store (reducer.js).

import { combineReducers } from 'redux'
import exampleReducers from "./exampleReducers";
const reducers = combineReducers({
example: exampleReducers,
});
export default reducers;

Here, as an example, there is just one reducer that is added to the store (exampleReducers.js).

import exampleTypes from './exampleTypes';

const initialState = {
name: '',
age: 0,
}

const exampleReducers = (state = initialState, action) => {
switch (action.type) {
case exampleTypes.CHANGE_NAME:
return {
...state,
name: action.payload
}
case exampleTypes.CHANGE_AGE:
return {
...state,
age: action.payload
}
default:
return state;
}
}

export default exampleReducers;

As you can see, the reducer function is a pure function that returns the updated state. In the above example, there are two different types that can change the state, CHANGE_NAME for changing the name, and CHANGE_AGE for changing the age.

It shows the available action types. For example, there are two different types CHANGE_NAME and CHANGE_AGE:

const exampleTypes = {
CHANGE_NAME: `CHANGE_NAME`,
CHANGE_AGE: `CHANGE_AGE`,
}
export default exampleTypes;

Actions are pure functions that return action objects (type and payload) based on the input arguments (exampleActions.js)

import exampleTypes from "./exampleTypes";
const exampleActions = {
changeName: (name) => ({
type: exampleTypes.CHANGE_NAME,
payload: name
}),
changeAge: (age) => ({
type: exampleTypes.CHANGE_AGE,
payload: age
}),
}

export default exampleActions;

Selectors are pure functions that take the redux state and return the derived data from the state (exampleSelectors.js).

const exampleSelectors = {
getName: (state) => state.example.name,
getAge: (state) => state.example.age,
}

export default exampleSelectors

How to use in react functional component

For dispatching an action, you need to write:

const dispatch = useDispatch();
dispatch(exampleActions.changeName('Test'))

And for getting the value of the variable in the state we use useSelector:

const name = useSelector(exampleSelectors.getName);

Finally, this is how to dispatch an action and show an state value on a react component (App.js):

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import exampleSelectors from './exampleSelectors';
import exampleActions from './exampleActions';

const App = () => {
const dispatch = useDispatch();
const name = useSelector(exampleSelectors.getName);
const age = useSelector(exampleSelectors.getAge);

useEffect(()=>{
dispatch(exampleActions.changeName('Test'))
dispatch(exampleActions.changeAge(20))
}, []);

return (
<>
<div>Name: ${name}</div>
<div>Age: ${age}</div>
</>
);
}

export default App;

The next step is adding Redux Saga: click here

Web Developer