Contextism 🤩 is a new way to use React Context better.
Read this article to become familiar with the idea.
Installation 🔥
npm i contextism// or yarn add contextism
Usage ✏️
We have two ways to use Contextism, Creating store using it or using its hooks directly:
#1 createStore ✋
// store.js ;const context = ;const Provider useDispatchContext useStateContext useStore = context; // App.jsx; const App = { const state dispatch = React; // or useReducer return <Provider state=state dispatch=dispatch> // Components you want to use the state there. <Div /> </Provider> } // Div.jsx; const Div = { const state = ; // "Value for state" const dispatch = ; // dispatch function (setState) in App // or better one const state dispatch = ; return ...}
When we create store using Contextism, it gives us 3 hooks :
-
useStateContext: the state value that we gave it to state prop in Provider component
-
useDispatchContext: the setState function or useReducer dispatch that we passed it to dispatch prop
-
useStore: returns us an array with two values of the above hooks;
[ useStateContext, useDispatchContext ]
NOTE: you should use these hooks( methods of createStore function) in child components of Provider component.
#2 default hooks ✋
Contextism has two hooks beside createStore function:
- useContext: takes a React context and returns the value
- useStore: takes two React contexts and returns two values of them, the same thing like in the above way but with two arguments
// Store.jsxconst CountStateContext = React;const CountDispatchContext = React; { ...} { const state dispatch = React; return <CountStateContextProvider value=state> <CountDispatchContextProvider value=dispatch> children </CountDispatchContextProvider> </CountStateContextProvider> }// App.jsx;; { return <CountProvider> <Div /> </CountProvider> }// Div.jsx;; { const state = ; const dispatch = ; // Or much better: const state dispatch = ; return ... }
Typescript 🔷
Contextism has Typescript support like generics and ... . in createStore you can pass two generics too, first one for the state structure and interface, the second one for the useReducer hook.
type Action = type: 'increment' | type: 'decrement'type State = count: number // The second generic is for useReducer Actionconst context = createStore<State Action>; // For useState just pass the first generic (State interface generic)const context = createStore<State>;
Contribution
I'm developer, not a perfect person, so I make much mistakes, it means that be free to create issues and then PRs.
Thanks ❤️
Special thanks for contributing and using this project.