7

What Is React Redux and How Do You Use it?

 2 years ago
source link: https://www.makeuseof.com/how-to-use-redux/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

What Is React Redux and How Do You Use it?

By Kadeisha Kean

Published 19 hours ago

Manage React state with ease using Redux. Ready to get started? Here's how.

Redux is a free state management library that works on the front-end of JavaScript applications, managing the state of each component within a UI. The Redux library facilitates a separation between code that manages and stores data in an application, and code that manages events and their effects on the various components of an application’s UI.

One of the main selling points of Redux is that it's flexible. You can use Redux with nearly any JavaScript framework or library.

The Redux team has created three libraries, namely Redux, React-Redux, and Redux Toolkit. All three libraries work together to give you the most out of your React development experience, and in this tutorial article, you’ll learn how to use them.

The Importance of React-Redux

Though Redux is an independent state management library, using it with any front-end framework or library requires a UI binding library. A UI binding library handles the state container (or store) interaction logic, which is a set of predefined steps that connects a front-end framework to the Redux library.

React-Redux is the official Redux UI binding library for React applications, and it’s maintained by the Redux team.

Related: How to Create Your First React App With JavaScript

Installing Redux in Your Project Directory

There are two ways to gain access to the Redux library in your React application. The recommended approach by the Redux team is to use the following command when creating a new React project:

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

The command above automatically configures the Redux Toolkit, React-Redux, and the Redux store. However, if you want to use Redux in an existing React project, then you can simply install the Redux library as a dependency with the following command:

npm install redux

Followed by the React-Redux binding UI library:

npm install react-redux

And the Redux toolkit:

npm install @reduxjs/toolkit

The Redux Toolkit library is also important because it makes the Redux store configuration process quick and easy.

Creating a Redux Store

Before you can start working with the Redux library, you’ll need to create a Redux state container (or store). Creating a Redux store is necessary because it’s the object that stores the global Redux application state.

React, like most front-end frameworks, has an entry point in its applications, which is a file or group of files at the top level. The index.html and index.js files are two files that are at the top level of a React app, which is above the App.js file and all the components in the app.

So, the index.js file is the ideal place to create a Redux store.

Updating index.js With the Redux Store

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import reportWebVitals from "./reportWebVitals"
import {configureStore} from "@reduxjs/toolkit"
import { Provider } from 'react-redux'
import user from './reducers/user'
const store = configureStore({
reducer:{
user
}
})
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
)
reportWebVitals();

There’s a lot to unpack in the code above, but the best place to start is with the configureStore function. Immediately you’ll start to see the benefits of installing the Redux Toolkit library as the configureStore function creates the Redux store with just three lines of code.

Your React application wouldn’t know that the Redux store exists without the provider component, which comes from the React-Redux binding library. The provider component takes a single prop (the store) and wraps itself around the React app, making the Redux store globally accessible.

The third and final new import in the index.js file above is the user reducer, which is vitally important to the operation of your Redux store.

Why Is a Reducer Important?

The purpose of a reducer is to change a UI component state based on a performed action. For example, if you’re creating an online school application, you'll require that each user signs into the application to gain access using a sign-in component. Another great component for this application is an active user component, which will display each user’s name or email address when they sign into your application.

In the example above, the active user component will change each time a user performs the action of signing into their account. This example is, therefore, an ideal situation for a reducer. It’s also important to remember that a reducer can only perform its function because of the Redux store that gives it access to the state of any component and the action it needs to carry out its duties.

Creating the User Reducer

import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name: "user",
initialState: { value: {email: ""}},
reducers: {
login: (state, action) => {
state.value = action.payload
},
}
})
export const {login} = userSlice.actions
export default userSlice.reducer;

Within React’s src directory you can create a reducer directory,which is where you’ll store your user reducer and any other reducer you want to add to your Redux store. The user.js file above imports the createSlice function from the Redux Toolkit.

The createSlice function accepts a name, an initial state, and a reducer object that stores multiple reducer functions. However, the reducers object above only has one reducer function called login that takes a state and an action as arguments and returns a new state.

The user.js file exports the login reducer. The sign-in component imports it and uses it in the useDispatch() hook.

Creating the Sign-In Component

import React from 'react';
import Link from '@mui/material/Link';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import { Button, Box } from '@mui/material';
import { useDispatch } from 'react-redux';
import { login } from '../reducers/user';
import { useState } from 'react';
function Signin() {
const dispatch = useDispatch()
const [email, setEmail] = useState('')
const handleSubmit = () => {
dispatch(login({email: email}))
}

return (
<div>
<Box
sx={{
my: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}>
<Typography variant="h4"> Sign In </Typography>
<TextField
label="Email Address"
required
id="email"
name="email"
margin="normal"
onChange={(e) => setEmail(e.target.value)}
/>
<TextField
label="Password"
required
id="password"
name="password"
type="password"
margin="normal"
/>
<Link
href="#"
sx={{mr: 12, mb: 2}}
>
forget password?
</Link>
<Button
variant="contained"
sx={{mt: 2}}
onClick={handleSubmit}
>
Sign In
</Button>
</Box>
</div>
);
}
export default Signin;

The sign-in component above uses the MUI library. It creates a simple sign-in form that requires a user’s email and password. Clicking the sign-in button will trigger an onClick function, which will call the handleSubmit function.

The handleSubmit function uses the useState() and useDispact() hooks along with the login reducer to make an active user’s email address available in the Redux store. From the Redux store, every component in the React app now has access to an active user’s email.

Related: Hooks: The Hero of React The following active user component retrieves an active user’s email address with the help of the useSelector() hook and renders it to the app UI.

The ActiveUser.js File

import React from "react";
import { useSelector } from "react-redux";

function ActiveUsers() {
const user = useSelector((state) => state.user.value)
return (
<div>
<h2>Active Users</h2>
<p> {user.email} </p>
</div>
);
}

The Updated App.js File

Take a look at this bit of code:

import React from "react"; import ActiveUsers from "./components/ActiveUsers"; import Signin from "./components/Signin";
function App() {
return ( <div> <ActiveUsers/> <Signin/> </div>
);
}
export default App;

The App.js file above renders both the active users and sign-in components in your React application creating the following output in your browser:

React Redux UI

If a user signs into the application, the active users component will immediately update with a new active user email.

The Updated UI

React Redux updated UI

When Should You Use Redux?

Redux is one of the most popular state management libraries, mainly because it does an excellent job of creating predictable and reliable code. If many components in an application use the same application state, Redux is the ideal choice.

Using the school example above, the sign-in component, active user component, class participant component, and even a profile component will need a user’s email address (or some other unique identifier). This is why Redux is the best option here.

However, if you have a state that’s only used by one or two components at most, then a better option may be React props.

About The Author

604a585247210-Kadeisha-profile-picture.jpg?fit=crop&w=100&h=100

Kadeisha Kean (36 Articles Published)

Kadeisha Kean is a Full-Stack Software Developer and Technical/Technology Writer. She has the distinct ability to simplify some of the most complex technological concepts; producing material that can be easily understood by any technology novice. She is passionate about writing, developing interesting software, and traveling the world (through documentaries).

More From Kadeisha Kean

Subscribe to our newsletter

Join our newsletter for tech tips, reviews, free ebooks, and exclusive deals!

Click here to subscribe

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK