Skip to content

Global State Management in React.js #13113

Closed Answered by smartcoder0305
cooldevstar asked this question in General
Discussion options

You must be logged in to vote

Sure! Here are some sample codes for each of the methods mentioned above:

React Context API

import { createContext, useContext, useState } from "react";

//create context
const GlobalContext = createContext();

//Wrapper component to initialize global state
const GlobalProvider = ({ children }) => {
  const [count, setCount] = useState(0);

  return (
    <GlobalContext.Provider value={{ count, setCount }}>
      {children}
    </GlobalContext.Provider>
  );
};

//Custom hook to consume global state
const useGlobalCounter = () => useContext(GlobalContext);

//Example usage
const MyComponent = () => {
  const { count, setCount } = useGlobalCounter();

  return (
    <div>
      <p>Count: {c…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@codemagician007
Comment options

@smartcoder0305
Comment options

Answer selected by cooldevstar
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants