TYPESCRIPT | useState
// 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} />;
}
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;