micael Copyright ©Softwave Marketing 2024

State Management with Context API

State management is crucial for developing dynamic web applications. The Context API in React allows you to manage global state that can be accessed by any component in your application. Here, we'll demonstrate how to set up and use the Context API for state management in "Startup."

Setting Up Context

First, let's create a context file that will contain our global state and the functions to update it:

// StateContext.js
import React, { createContext, useContext, useReducer } from 'react';

// Define the initial state
const initialState = {
  count: 0,
  user: null,
};

// Create a context
const StateContext = createContext();

// Create a reducer to handle state updates
const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    case 'SET_USER':
      return { ...state, user: action.payload };
    default:
      return state;
  }
};

// Create a context provider component
const StateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <StateContext.Provider value={{ state, dispatch }}>
      {children}
    </StateContext.Provider>
  );
};

// Create a custom hook for accessing the context
const useStateValue = () => {
  const context = useContext(StateContext);
  if (!context) {
    throw new Error('useStateValue must be used within a StateProvider');
  }
  return context;
};

export { StateProvider, useStateValue };

Using the Context Provider

Wrap your entire application with the StateProvider to make the global state available to all components:

// App.js
import React from 'react';
import { StateProvider } from './StateContext';
import Counter from './Counter';
import User from './User';

function App() {
  return (
    <StateProvider>
      <div className="App">
        <h1>State Management with Context API</h1>
        <Counter />
        <User />
      </div>
    </StateProvider>
  );
}

export default App;

Accessing and Modifying State

Now, you can easily access and modify the global state in any component using the useStateValue hook:

// Counter.js
import React from 'react';
import { useStateValue } from './StateContext';

function Counter() {
  const { state, dispatch } = useStateValue();

  const increment = () => {
    dispatch({ type: 'INCREMENT' });
  };

  const decrement = () => {
    dispatch({ type: 'DECREMENT' });
  };

  return (
    <div>
      <h2>Counter</h2>
      <p>Count: {state.count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

export default Counter;
// User.js
import React from 'react';
import { useStateValue } from './StateContext';

function User() {
  const { state, dispatch } = useStateValue();

  const setUser = () => {
    dispatch({ type: 'SET_USER', payload: { name: 'John Doe' } });
  };

  return (
    <div>
      <h2>User</h2>
      <p>User: {state.user ? state.user.name : 'Not logged in'}</p>
      <button onClick={setUser}>Set User</button>
    </div>
  );
}

export default User;

Conclusion

The Context API in React, as demonstrated in this example, provides a powerful way to manage global state in your "Startup" front-end applications. By using the StateProvider and the useStateValue hook, you can efficiently handle and share state among different components, enabling you to build dynamic and interactive web applications with ease.