init-store
v1.0.12
Published
use context with easy library in React function component
Downloads
4
Readme
init-store
use context with easy library in React function component
usage
- initialize store in base
import initStore from "init-store";
export const { Context, Provider } = initStore();
- use in function component
export default function App() {
// store controller with store & setStore
const [store, setStore] = React.useState({ count: 1 });
return (
// provider
<Provider value={{ store, setStore }}>
<div className="App">
Title
<LayerAlpha />
<LayerBeta />
</div>
</Provider>
);
}
- use in son component
export function LayerAlpha() {
const { store, setStore } = React.useContext(Context);
return <div>LayerAlpha {store.count}</div>;
}
export function LayerBeta() {
const { store, setStore } = React.useContext(Context);
return (
<div>
<button onClick={() => setStore({ count: ++store.count })}>
LayerBeta
</button>
</div>
);
}
- overview
import React from "react";
export type StoreType = {
count: number;
};
export const { Context, Provider } = initStore<StoreType>();
export function LayerAlpha() {
const { store, setStore } = React.useContext(Context);
return <div>LayerAlpha {store.count}</div>;
}
export function LayerBeta() {
const { store, setStore } = React.useContext(Context);
return (
<div>
<button onClick={() => setStore({ count: ++store.count })}>
LayerBeta
</button>
</div>
);
}
export default function App() {
const [store, setStore] = React.useState<StoreType>({
count: 1,
});
return (
<Provider value={{ store, setStore }}>
<div className="App">
Title
<LayerAlpha />
<LayerBeta />
</div>
</Provider>
);
}