1.0.2 • Published 4 years ago

react-hook-use-global-state v1.0.2

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

React Hook - useGlobalState

NPM

Simple Global State Hook for React

Install

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

import React from "react"
import { StateProvider } from "react-hook-use-global-state"

const initialState = {
  counter: 0
}

const reducer = (state, action) => {
  switch (action.type) {
    case "counterInc":
      return {
        ...state,
        counter: state.counter + 1
      }
    case "counterDec":
      return {
        ...state,
        counter: state.counter - 1
      }
    default:
      return state
  }
}

export default function Layout({ children }) {
  return (
    <StateProvider initialState={initialState} reducer={reducer}>
      {children}
    </StateProvider>
  )
}

Use the global state in your component.

SomeComponent.js

import React from "react"
import { useGlobalState } from "react-hook-use-global-state"

export default function SomeComponent() {
  const [{ counter }, dispatch] = useGlobalState()
  return (
    <div>
      Count: {counter}
      <br />
      <button onClick={() => dispatch({ type: "counterInc" })}>Inc</button>
      <button onClick={() => dispatch({ type: "counterDec" })}>Dec</button>
    </div>
  )
}