Inspired by react-context-io, based on react hooks, useContext and createContext to share state between components, and also provide global states tree to get different context state.
中文移步
npm i react-stores-hooksimport React from "react"; import { createContext, useContext, useDispatchContext } from "react-stores-hooks"; const Result = () => { const { age, name }: any = useContext("person"); return ( <div> <div>name:{name}</div> <div>age:{age}</div> </div> ); }; const AddButton = () => { const { dispatch } = useDispatchContext("person"); const addAgeHandle = () => { dispatch((data: any) => ({ ...data, age: data.age + 1 })); }; return <button onClick={addAgeHandle}>increase age</button>; }; const Person = () => { const Provider = createContext({ namespace: "person", initialState: { age: 18, name: "harry" } }); return ( <Provider> <Result /> <AddButton /> </Provider> ); }; export default Person;-
createContextregistered a context
- Options
- namespace
- initialState
- Return
- Provider a Provider component
- Options
-
ContextProvidercreate a Provider,call createContext inside
- props
- namespace
- initialState
- children
- props
-
useContextGet the specified context
- Argument
- namespace
- Return
- state
- getState
- Argument
-
useDispatchContextGet the specified context
- Argument
- namespace
- Return
- dispatch a function that dispatch a new state to update the state
- setState
- Argument
-
useGlobalContextGet all contexts
Return object[]
-
deleteContextdelete the specified context