项目作者: HashDot

项目描述 :
React Hook - Simple Global State with React Context
高级语言: JavaScript
项目地址: git://github.com/HashDot/react-hook-use-global-state.git
创建时间: 2020-01-16T20:59:39Z
项目社区:https://github.com/HashDot/react-hook-use-global-state

开源协议:MIT License

下载


React Hook - useGlobalState

NPM

Simple Global State Hook for React

Install

  1. npm i react-hook-use-global-state

Usage

Add the provider to your layout or HoC and define your initial state and
your reducer.

Demo:

Edit Demo

Layout.js

  1. import React from "react"
  2. import { StateProvider } from "react-hook-use-global-state"
  3. const initialState = {
  4. counter: 0
  5. }
  6. const reducer = (state, action) => {
  7. switch (action.type) {
  8. case "counterInc":
  9. return {
  10. ...state,
  11. counter: state.counter + 1
  12. }
  13. case "counterDec":
  14. return {
  15. ...state,
  16. counter: state.counter - 1
  17. }
  18. default:
  19. return state
  20. }
  21. }
  22. export default function Layout({ children }) {
  23. return (
  24. <StateProvider initialState={initialState} reducer={reducer}>
  25. {children}
  26. </StateProvider>
  27. )
  28. }

Use the global state in your component.

SomeComponent.js

  1. import React from "react"
  2. import { useGlobalState } from "react-hook-use-global-state"
  3. export default function SomeComponent() {
  4. const [{ counter }, dispatch] = useGlobalState()
  5. return (
  6. <div>
  7. Count: {counter}
  8. <br />
  9. <button onClick={() => dispatch({ type: "counterInc" })}>Inc</button>
  10. <button onClick={() => dispatch({ type: "counterDec" })}>Dec</button>
  11. </div>
  12. )
  13. }