Getting Started with Redux

Getting Started with Redux

ยท

4 min read

Content


Why use Redux?

Redux is used for state management. It is used to pass the state of one component into other components.

Why not to use Redux?

  • It has a lot of boiler plate code
  • It has a pretty big size
  • It is over-complicated for simple tasks

Step by Step Implementation of Redux

  • Install redux, react-redux and @reduxjs/toolkit
๐Ÿ’ก Perform the below tasks in index.js file
  • Create a Store: Store is basically the place for storing all the variables in redux. It is created by using:

      import {configureStore} from '@reduxjs/toolkit';
    
      const store= configureStore({
          reducer: {}
      })
    
    • configureStore

      This is used to create stores in redux

  • Create Provider: Provider basically denotes which component should contain the global states which can be accessed by all other components

      import {configureStore} from '@reduxjs/toolkit';
      import {Provider} from 'react-redux';
    
      function LearnReducer() {
      const store= configureStore({
      reducer: {}
      });
    
      return(
          <>
          <Provider store={store}>
              <App />
          </Provider>
          </>
      )
      }
    
  • Create Reducers: Reducers are basically the variables which takes in the states that we want to make global and also the function of actions that we want to perform on changing the values of the states

    Create a folder called features and then create files for each reducers that we want to create

    Suppose I want to create a reducer which will contain the states of a user during login like his name, age and email. I also want to create actions such that the value of the initial state changes

    Inside features folder and file is user.js

      import {createSlice} from '@reduxjs/toolkit';
    
    • createSlice

      • It helps in creating reducers in an organised way.
      • It helps in separating out the content between the states and the different actions
      • It takes in
        • name: which contains the states that we want to make global
        • initialState: which contains the specifics of the data that we want to work with
        • reducers: which contains the actions that we want to perform on the given states
      export const userSlice= createSlice({
        name: "user",
        initialState: {value: { name: "", age: 0, email: "" }}
        reducers: {
            login: (state, action) => {
                state.value = action.payload
            }
        }
      })    
      
      export const {login} = userSlice.actions;
      
      export default userSlice.reducer;
      

      The functions created under the reducers key have two parameters

      • state: this contains the state mentioned in the initialState
      • action: this contains two params within itself
        • payload: this is used to send new values of the states
        • type: this is used to specify the type of the action this is especially helpful for working with conditional parameters
      state.value = actions.payload
      

      the above snippet is basically taking the initial state and changing it with the new values provided by other components

      export default userSlice.reducer;
      

      The above snippet give us the access of the name and initialState of the reducer

      export const {login} = userSlice.actions;
      

      The above snippet is used to export the actions created inside the reducer

      ๐Ÿ’ก After creating the reducer we will have to add the reducer in the store
      import {configureStore} from '@reduxjs/toolkit';
      import userReducer from 'file containing user.js';
      
      const store= configureStore({
        reducer: {
            user: userReducer,
        }
      })
      

      Accessing the value of the reducer in a component

      Suppose we want to display the name, age and email of the user with the states as created in the reducer

      import {userSelector} from 'react-redux';
      
    • userSelector

      This is used to access the states inside the reducer

function Profile() {
    const user= useSelector((state) => state.user.value);

  return (
    <div>
      <h1>Profile</h1>
      <h2>Name: {user.name} </h2>
      <h2>Age: {user.age}</h2>
      <h2>Email: {user.email}</h2>
    </div>
  );
}

export default Profile;

Now we want to create a button which on click will update the state of the reducer with new values

๐Ÿ’ก We create a new file named Login.js for the button

import {useDispatch} from 'react-redux';
  • useDispatch
    • This is used to access the action functions that we have created within the reducer.
    • This is used to change the initial value with the new values provided from components
import {login} from 'file containing the user.js file';
 const dispatch= useDispatch();

    function Login() {
      return (
        <div>
          <button onClick={() => dispatch(login({name:"Rohit", age: "20", email: "rohitpurkait001@gmail.com"}))}>Login</button>
        </div>
      );
    }

    export default Login;

Did you find this article valuable?

Support Rohit Purkait by becoming a sponsor. Any amount is appreciated!

ย