To integrate Redux into a React application, you need to install the required packages:
npm install @reduxjs/toolkit
npm install react-redux
The Store is a centralized place where all global states of your application are managed. It holds the entire state tree of the application and allows components to access and update the state in a predictable manner. To start using the store, you need to configure it using the configureStore() function provided by Redux Toolkit.
A Reducer is a function that takes in two arguments: the current state and an action. Based on the action type, it returns a new state. Reducers are responsible for updating the state in response to actions dispatched to the store. In the Redux Toolkit, reducers are typically created using the createSlice() function, which automatically generates actions and action creators, simplifying the process of writing Redux logic.
The Provider component is similar to the Context Provider in the Context API. It wraps around the components that need access to the Redux store. The Provider makes the Redux store available to any nested components that need to access the state or dispatch actions.
// store.js
import { configureStore, createSlice } from "@reduxjs/toolkit";
const initialState = { value: { username: "" } };
const userSlice = createSlice({
name: "user",
initialState,
reducers: {
login: (state, action) => {
state.value = action.payload;
},
logout: (state) => {
state.value = { username: "" };
}
}
});
export const { login, logout } = userSlice.actions;
export const store = configureStore({
reducer: {
user: userSlice.reducer
}
});
name, initialState, and reducers properties.
name: A unique name for the slice.initialState: The initial state value for the slice.reducers: An object where keys are reducer names and values are reducer functions. These functions define how to update the state based on actions.createSlice.The Provider component makes the Redux store available to any nested components that need to access the Redux state.
// index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { store } from "./store";
import App from "./App";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);