4. State management: props , context , redux

Ayush RajputAyush Rajput
3 min read
  1. State

    • State is a built-in object in React components that stores dynamic data.

    • State is mutable (can be changed using setState or useState).

    • Changing state re-renders the component.

  1. Props

    • Props (short for “Properties”) are used to pass data from parent to child components.

    • Props are immutable (cannot be changed by the child component).

    • They help in component reusability.

  1. Prop Drilling

    • Prop Drilling occurs when data is passed through multiple layers of components only to reach a deeply nested child component.

    • This leads to unnecessary prop passing, making the code harder to maintain.

      How to Fix Prop Drilling?

      ✅ Use Context API
      ✅ Use Redux for global state

  1. Context API (Built-in State management in react)

    React’s Context API provides a way to pass data down the data in component tree without using props.

    It uses useContext() Hook

    Steps to Use Context API

    1. Create a Context

    2. Provide the Context Value

    3. Consume the Context Value in Components

    //Step 1: Create context:  create context folder - inside AppContext.js file
    export const AppContext = createContext(null) // create context

    export function AppContextProvider ({children}){ // here children is our </App> that bound in index.js
     const [cartItems, setCartItems]= useState({}); // 1.write all reusable states here
      const [token , setToken] = useState("");
      //2.write reusable functions
      //3. Also manage authentication by getting and setting token from local storage
      //4.
      const value = {
       cartItems , 
       setToken
       }
    //5.
      return (
            <AppContext.Provider value={value}>
                {children}
            </AppContext.Provider>
          )
      }
    //Step 2:  Next step is to wrap </App> inside<AppContextProvider> in index.js
    // STEp 3: use these context values in components
    import React, { useContext } from "react";
    import { UserContext } from "./UserProvider";

    function Profile() {
      const user = useContext(UserContext);
      return <h1>Welcome, {user}!</h1>;
    }

    export default Profile;
  1. Redux

    Redux is a predictable state management library for React applications. It manages global state and makes data flow easier.
    This is generally used in large scale applications.

    Step wise step implementation:

    Step 1: Install redux toolkit and react redux

     npm install @reduxjs/toolkit react-redux
    

    Step 2: Create Slices

     import { createSlice } from "@reduxjs/toolkit"
     const initialState = {
         signupData : null,
         loading : false,
         token: localStorage.getItem("token") ?  JSON.parse(localStorage.getItem("token")) : null, // import by UseSelector
     }
     const authSlice = createSlice({
         name:"auth",
         initialState:initialState, // import initial states by using useSelector()
         reducers:{
             setSignupData(state, value){
                 state.signupData = value.payload
             },
    
             setLoading(state,value){
                 state.loading=value.payload
             },
    
             setToken(state,value){
                 state.token= value.payload
             },
             increment: (state) => { state.value += 1; }, // we also write callback function like this
         }
     })
     export const {setSignupData , setLoading , setToken} = authSlice.actions; // import by using useDispatch()
     export default authSlice.reducer  // import authSlice in store
    

    Step 3: Create store link all slices in store

     import { configureStore } from "@reduxjs/toolkit";
     import authReducer from "./authSlice"; // import authSlice
     import profileReducer from "./profileSlice"
    
     const store = configureStore({
       reducer: {
         auth: authReducer,
         profile:profileReducer,
       },
     });
     export default store;
    

    Step 4: Provide store in 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")
);

Step 5: Access Redux states in components

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

function Counter() {
  const{token , signupData} = useSelector((state)=>state.auth)
  const dispatch = useDispatch();
  return (
    <div>

      <button onClick={() => dispatch(dispatch(setSignupData()}>+</button>
      <button onClick={() => dispatch(increment())}>-</button>
    </div>
  );
}
export default Counter;

InterView Questions

  1. How to solve prop Drilling ?

    By the use of : Context API or Redux

  2. What are the benifits of redux ?

    ✅ Centralized state management
    ✅ Predictable state changes
    ✅ Scalable for large apps

  3. When to use Redux instead of Context API ?

    Use Context API for small applications.
    Use Redux for large applications with complex state logic.

Next Topic : SEO in React

0
Subscribe to my newsletter

Read articles from Ayush Rajput directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ayush Rajput
Ayush Rajput