Wednesday, July 3, 2024
HomeLanguagesReactHow to set initial state in Redux ?

How to set initial state in Redux ?

In ReactJS, redux is the tool for the management of the state throughout the whole application globally. The state that we use inside redux as a store can only be modified with the help of the actions. But, this state must be specified somewhere first to use it. 

We prefer to declare our initial state at the reducer files. Then we use that reducer in the store and provide that store use inside the whole application.

Let’s create an application in react with redux and set the initial state there:

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app example

Step 2: After creating your project folder i.e. example, move to it using the following command:

cd example

Step 3: Module installation, now from the root directory of your project in the terminal, run the following command

npm install redux
npm install react-redux

Step 4: In src folder, make two new folder components and redux. In components add two jsx files named content.jsx and header.jsx. In the redux folder, create a folder name actions and add actions.js file to it. Then in the redux folder create a folder name reducer and add two files named reducer.js and rootreducer.js. And then in the redux folder add store.js file.

Project Structure: It will look like this.

project structure

Example: Let’s make a simple application with help of redux. Write down the following codes in respective files.

Javascript




//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
 
ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById('root')
);


App.js

Javascript




//App.js
import React from "react";
import { Provider } from "react-redux";
import Content from "./components/content";
import Header from "./components/header";
import store from "./redux/store";
 
function App() {
    return (
        <Provider store={store}>
            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    justifyContent: "center",
                    height: "100vh",
                }}
            >
                <Header />
                <Content />
            </div>
        </Provider>
    );
}
 
export default App;


components/content.jsx

Javascript




import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
 
import { login, logout, increment, decrement }
    from '../redux/actions/actions';
 
export default function Main() {
    const count = useSelector(state => state.count.counter);
    const signed = useSelector(state => state.auth.signed);
    const dispatch = useDispatch();
 
    return (
        <div style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
 
        }}>
            <h1>Total count: {count}</h1>
 
            <div>
                <button onClick={() => dispatch(decrement(2))}>-2</button>
                <button onClick={() => dispatch(increment(2))}>+2</button>
            </div>
 
            {signed ? (
                <button onClick={() => dispatch(logout())}>LOGOUT</button>
            ) : (
                <button onClick={() => dispatch(login())}>LOGIN</button>
            )}
        </div>
    );
}


components/header.js

Javascript




import React from "react";
import { useSelector } from "react-redux";
 
export default function Header() {
    const signed = useSelector(state => state.auth.signed);
 
    return (
        <div signed={signed}>
            <h1>Logged in: {String(signed)}</h1>
        </div>
    );
}


redux/actions/actions.js

Javascript




export function login() {
    return {
        type: "@auth/LOGIN"
    };
}
 
export function logout() {
    return {
        type: "@auth/LOGOUT"
    };
}
 
export function increment(number) {
    return {
        type: "@auth/INCREMENT",
        payload: number
    };
}
 
export function decrement(number) {
    return {
        type: "@auth/DECREMENT",
        payload: number
    };
}


redux/reducer/reducer.js

Javascript




import produce from "immer";
 
const INITIAL_STATE = {
    signed: false,
    counter: 0
};
 
export default function auth(state = INITIAL_STATE, action) {
    return produce(state, draft => {
        switch (action.type) {
            case "@auth/LOGIN":
                draft.signed = true;
                break;
            case "@auth/LOGOUT":
                draft.signed = false;
                break;
            case "@auth/INCREMENT":
                draft.counter += action.payload;
                break;
            case "@auth/DECREMENT":
                draft.counter -= action.payload;
                break;
            default:
        }
    });
}


Here, we have declared our initial state and initialized them with some default values.

redux/reducer/rootreducer.js

Javascript




import { combineReducers } from "redux";
 
import auth from "./reducer";
import count from "./reducer";
 
export default combineReducers({
    auth,
    count
});


redux/store.js

Javascript




import { createStore } from "redux";
import rootReducer from "./reducers/rootreducer";
 
const store = createStore(rootReducer);
 
export default store;


Step to run the application: Use the following command to run the application:

npm start

Output:

There are two initial states in this example which are defined in the reducer file of redux.

  • signed: false,
  • counter: 0

which are changing by actions.

Output

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments