Redux is an open-source JavaScript library that is widely used for managing state in complex applications. also, it provides a centralized store that holds the state of an entire application and enables easy management of state changes.
State Type
- Local State – State that belongs to a single component.
- Cross-Component State – State that affects multiple components.
- App-Wide State – State that affects the entire app ( most all components ).
How does Redux work?
Redux works on the following principles and terms.
Store – The current redux application state lives in an object called the store that is created by passing the reducer as prams. Also provide some methods for access and modify the state values.
Actions – Action in redux is the object that holds the type key with its value and payload additional data that help to perform the action that descript in reducers.
Reducers – A reducer is a function that receives the current state and an action object.
The reducer also handles events based on the action type received that are dispatched.
Dispatch – Dispatch is the only way to update the state based on passing in an action object.
also we can call triggering and event.
Selectors – Are functions that help to extract or get specific information from
a store state value.
You need to install the redux and react-redux packages:
npm install redux react-redux
Note: If you want to follow my folder structure or your-self its depend on you.
Inside the src folder create reduxContainer folder and add new file store.js add this code.
import { createStore } from "redux"; import BookReducer from "./BookReducer"; const store = createStore(BookReducer); export default store;
ref: crateStore
Add new file BookReducer.js inside same directory
const initState = { NumberOfBooks: 25 }; const BookReducer = (state = initState, action) => { switch (action.type) { case "buyBook": return { ...state, NumberOfBooks: state.NumberOfBooks - 1 }; case "addBook": return { ...state, NumberOfBooks: state.NumberOfBooks + 1 }; default: return state; } }; export default BookReducer;
add BookContainer.js component in same dir.
import React from "react"; import { useSelector, useDispatch } from "react-redux"; function BookContainer() { const nofb = useSelector((state) => state.NumberOfBooks); const dispatch = useDispatch(); const buy = () => { dispatch({ type: "buyBook" }); }; const add = () => { dispatch({ type: "addBook" }); }; return ( <> <h3>Container Book - {nofb}</h3> <button onClick={buy}>BuyBook</button> <button onClick={add}>AddBook</button> </> ); } export default BookContainer;
ref: useSelector , useDispatch
Now you need to add BookContainer Component on your App Component for render.
Inside your main index.js file where the root render add the following code for adding you’re redux in React.
import store from "./reduxContainer/Store"; import { Provider } from "react-redux"; // add store object as props inside parent Provider Component with store attribute root.render( <Provider store={store}> <StrictMode> <App/> </StrictMode> </Provider> );
ref: Provider
Note: here is URL of full code.
React Redux + Redux Toolkit:
Ref URL for ‘React Redux + Redux Toolkit’ Example
npm install @reduxjs/toolkit react-redux
Redux Took-kit is way easier to implement redux in react js and also provides automation for some of the thinging that we need to add manually in redux.
configureStore does the following things automatically for us.
- Combined multiple reducers with single root ruducers.
- Add thunk middleware.
- More middleware for checking common mistakes like accidentally mutating the state.
- Setup redux DevTools extension connection.
Inside src folder create new folder call ‘components’ and inside ‘components’ folder create ‘store’ folder then create index.js file. and put the below code inside the file
import { createSlice } from "@reduxjs/toolkit"; const initialAuhtState = { isAuthenticated: false }; export const authSlice = createSlice({ name: "authorization", initialState: initialAuhtState, reducers: { login(state) { state.isAuthenticated = true; }, logout(state) { state.isAuthenticated = false; } } }); export const authoActions = authSlice.actions;
Note: createSlice function that accepts object that contains 3 major key are ‘names’,
‘initialState’, ‘reducers’.
Inside your main index.js file where the root render add the following code for adding you’re reduxjs/toolkit in React.
........ import { configureStore } from "@reduxjs/toolkit"; import { authSlice } from "./components/store/index"; import { Provider } from "react-redux"; const store = configureStore({ reducer: { auths: authSlice.reducer } }); root.render( <Provider store={store}> <App/> </Provider> );
ref: configureStore
Note. access this auths value using useSelector by state.auths.isAuthenticated like that.
create Auth.js file inside ‘components’ folder and add this code on it.
import classes from "./Auth.module.css"; import { useDispatch } from "react-redux"; import { login } from "./store/index"; const Auth = () => { const dispatch = useDispatch(); const loginHandle = () => { dispatch(login()); }; return ( <main className={classes.auth}> <section> <form> <button onClick={loginHandle}>Login</button> </form> </section> </main> ); }; export default Auth;
Inside App.js Component we can render UserProfile component based on isAuthenticated value that are store inside reduxjs/toolkit Store.
import { useSelector } from "react-redux"; import UserProfile from "./components/UserProfile"; function App() { const isAuth = useSelector((state) => state.auths.isAuthenticated); return ( <Fragment> <Header /> {isAuth && <UserProfile />} {!isAuth && <Auth />} </Fragment> ); }
Note: here is demo URL of full code.