Skip to content

Instantly share code, notes, and snippets.

@tattali
Last active July 12, 2022 08:29
Show Gist options
  • Save tattali/e56383dbca18322af7a4f3204bd6eddc to your computer and use it in GitHub Desktop.
Save tattali/e56383dbca18322af7a4f3204bd6eddc to your computer and use it in GitHub Desktop.
How to share data between components with react context

React Context as a store

TYPESCRIPT | useState

Context configuration

// src/services/context/StoreContext.tsx
import React, { createContext, Dispatch, PropsWithChildren, SetStateAction, useState } from "react";

export interface IStore {
  props1: string;
}

const defaultValue: IStore = {
  props1: "value1",
};

const defaultUpdate: Dispatch<SetStateAction<IStore>> = () => defaultValue;
export const StoreContext = createContext({
  state: defaultValue,
  update: defaultUpdate,
});
export function StoreProvider(props: PropsWithChildren<{}>) {
  const [state, update] = useState(defaultValue);
  return <StoreContext.Provider value={{ state, update }} {...props} />;
}

Usage

Wrap the components that need shared data from the provider.

Try to reduce the number of child components as best as possible.

// src/App.tsx
import React, { FC } from "react";
import Layout from "./components/Layout";
import { StoreProvider } from "./services/context/StoreContext";

const App: FC = () => {
  return (
    <StoreProvider>
      <Layout />
    </StoreProvider>
  );
}

export default App;

Use the useContext hooks to access and modify the shared data.

// src/components/Layout/index.tsx
import React, { FC, useContext } from "react";
import { StoreContext } from "./services/context/StoreContext";

const Layout: FC = () => {
  const { state, update } = useContext(StoreContext);

  return (
    <>
      <input type="text" value={state.props1} onChange={(e) => {
        update({ ...state, props1: e.currentTarget.value });
      } />
    </>
  );
}

export default Layout;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment