Big News: Socket Selected for OpenAI's Cybersecurity Grant Program.Details
Socket
Book a DemoSign in
Socket

react-root-context

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

react-root-context

root context

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

react-root-context

React Root Context

If you want to use React Context to separate the state from components, it can be challenging to manage contexts for the multiple data sources. This small library helps to create the root parenst single from children contexts, and pull the data up in separate contexts.

Installation

npm install react-root-context

Use

You need to create a React root context and pass it as a parameter to RootContext. This wraps around your children contexts, providing single parent RootContext.

import RootContext from 'react-root-context';
const root = React.createContext(null);
...

export default () => (
  <RootContext rootContext={root}>
    <App />
  </RootContext>
);

Example: codesandbox

import React, { useContext, useEffect } from "react";
import RootContext from "react-root-contexts";

const root = React.createContext(null);
const childContext1 = React.createContext(null);
const childContext2 = React.createContext(null);

const B = () => {
  const value1 = useContext(childContext1);
  return (
    <div>
      B=
      {value1}
    </div>
  );
};

const C = () => {
  const value2 = useContext(childContext2);
  return (
    <div>
      C=
      {value2}
    </div>
  );
};

function App() {
  const rc = useContext(root);
  useEffect(() => {
    rc.addChildrenContexts(["b", "c"], [childContext1, childContext2]);
  });
  return (
    <div className="App">
      <B />
      <C />
    </div>
  );
}

export default () => (
  <RootContext root={root}>
    <App />
  </RootContext>
);

FAQs

Package last updated on 08 Mar 2021

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