DEV Community

Cover image for Simplifying State Management : Using Context API with Session Storage instead of Redux
Ranga Dewasinghe
Ranga Dewasinghe

Posted on

Simplifying State Management : Using Context API with Session Storage instead of Redux

State management is a crucial aspect of building React applications. While Redux is a powerful and widely-used state management library, it may introduce unnecessary complexity in certain scenarios, particularly in less complex applications. In such cases, leveraging React's Context API along with session storage can provide a simpler and lightweight alternative for managing the application state. This article will guide you through the process of implementing the Context API with session storage in a step-by-step manner.


Step 1: Setting up the React Project
Create a new React project using TypeScript by running the following command:

npx create-react-app my-app --template typescript
cd my-app
Enter fullscreen mode Exit fullscreen mode

Step 2: Creating the Context
In the src folder, create a new file called AppContext.tsx. In this file, define the context and its initial state:

import React, { createContext, useEffect, useState } from 'react';

interface AppState {
  counter: number;
  // Add other state properties here
}

interface AppContextProps {
  appState: AppState;
  incrementCounter: () => void;
  resetCounter: () => void;
}

export const AppContext = createContext<AppContextProps | null>(null);

const AppProvider: React.FC = ({ children }) => {
  const [appState, setAppState] = useState<AppState>({
    counter: 0,
    // Initialize other state properties here
  });

  useEffect(() => {
    const storedState = sessionStorage.getItem('appState');
    if (storedState) {
      setAppState(JSON.parse(storedState));
    }
  }, []);

  useEffect(() => {
    sessionStorage.setItem('appState', JSON.stringify(appState));
  }, [appState]);

  const incrementCounter = () => {
    setAppState((prevState) => ({
      ...prevState,
      counter: prevState.counter + 1,
    }));
  };

  const resetCounter = () => {
    setAppState((prevState) => ({
      ...prevState,
      counter: 0,
    }));
  };

  return (
    <AppContext.Provider
      value={{ appState, incrementCounter, resetCounter }}
    >
      {children}
    </AppContext.Provider>
  );
};

export default AppProvider;

Enter fullscreen mode Exit fullscreen mode

Step 3: Providing State and Actions to Components
Wrap your application's root component with the AppProvider and provide the state and actions through the context:

import AppProvider from './AppContext';

function App() {
  return (
    <AppProvider>
      {/* Your application components */}
    </AppProvider>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 4: Consuming State and Actions in Components
To access the state and actions within your components, import the AppContext and use the useContext hook:

import React, { useContext } from 'react';
import { AppContext } from './AppContext';

const MyComponent: React.FC = () => {
  const { appState, incrementCounter, resetCounter } =
    useContext(AppContext)!;

  return (
    <div>
      <p>Counter: {appState.counter}</p>
      <button onClick={incrementCounter}>Increment</button>
      <button onClick={resetCounter}>Reset</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

By following these steps, you can implement the Context API with session storage in a TypeScript-based React application. Remember to adjust the state properties, actions, and components according to your specific application's needs.

You can find the complete implementation at https://github.com/nirmana/react-context-session-storage.

Happy coding!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)