use-root-reducer
A helper to create and maintain a global state without redux. (based on react hooks)
Install
$ npm i use-root-reducer --save
Usage
First of all, create a global state and a global dispatch function in your root component:
// app.jsximport React useReducer from "react";import useRootReducer from "use-root-reducer";import fooReducer barReducer from "./reducer";import StateContext DispatchContext from "./context"; const App = children const state dispatch = ; return <DispatchContext.Provider => <StateContext.Provider =>children</StateContext.Provider> </DispatchContext.Provider> ;; ;
You can pass your global state and global dispatch method (it will have foo
and bar
key-value in the above example) to your children components via props or with React Context API.
Second, it's recommended to maintain your context code in a independent file:
// context.jsximport React from "react"; const StateContext = React; const DispatchContext = React; const OtherContext = React;
In the end, in your child components you can access your global state and global dispatch with useContext
:
//import React from "react"; import StateContext DispatchContext from "./context.js"; const state = React; const dispatch = React; const foo bar = state; return <button = >` and `</button> ;;