New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

use-root-reducer

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-root-reducer

a helper to create and maintain a global state without redux. (based on react hook)

latest
Source
npmnpm
Version
1.0.1
Version published
Weekly downloads
31
244.44%
Maintainers
1
Weekly downloads
 
Created
Source

use-root-reducer

NPM version build status Test coverage npm download

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.jsx
import 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] = useRootReducer({
    foo: useReducer(fooReducer, "foo"),
    bar: useReducer(barReducer, "bar")
  });
  return (
    <DispatchContext.Provider value={dispatch}>
      <StateContext.Provider value={state}>{children}</StateContext.Provider>
    </DispatchContext.Provider>
  );
};

export default App;

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.jsx
import React from "react";

export const StateContext = React.createContext({});

export const DispatchContext = React.createContext(null);

export const OtherContext = React.createContext();

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";

export default () => {
  const state = React.useContext(StateContext);
  const dispatch = React.useContext(DispatchContext);

  const { foo, bar } = state;

  return (
    <button
      onClick={() => {
        // dispatch your action and will be received in all your reducers
        dispatch({ type: "update", payload: "foo updated", meta: "foo" });
      }}
    >{`${foo} and ${bar}`}</button>
  );
};

License

MIT

Keywords

react

FAQs

Package last updated on 11 Nov 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts