how do i create a global store using react context in typescript

To create a global store using React Context in TypeScript, you can follow these steps:

  1. Create a new TypeScript file for your context, say GlobalStore.tsx
  2. Import createContext from React and create a new context:
index.ts
import { createContext } from 'react';

interface ContextProps {
  // declare your state properties here
}

const GlobalStoreContext = createContext<ContextProps | undefined>(undefined);

export default GlobalStoreContext;
223 chars
10 lines
  1. In your App.tsx, wrap your application with the GlobalStoreContext.Provider, passing in your state properties and any actions/methods you want to use to update them:
index.ts
import React, {useState} from "react";
import GlobalStoreContext from './GlobalStore';

function App() {
  const [count, setCount] = useState(0);

  return (
    <GlobalStoreContext.Provider value={{ count, setCount }}>
      {/* your application code */}
    </GlobalStoreContext.Provider>
  );
}
298 chars
13 lines
  1. In your child components that need access to the global store, import the context and use the useContext hook to access your state:
index.ts
import React, { useContext } from "react";
import GlobalStoreContext from './GlobalStore';

const MyComponent = () => {
  const { count, setCount } = useContext(GlobalStoreContext);

  const incrementCount = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment Count</button>
    </div>
  );
};
379 chars
18 lines

That's it! You should now have a global store that can be accessed from any component in your application.

related categories

gistlibby LogSnag