Share Global State or Value Among React Components Easily

share state among react components

As you know in order to share common state among React components you need a framework like Redux or need to rely on other hard to learn technique. Here I am going to discuss with examples on how to share a global value or set of values (Common Store) among all react components. Every value used will be auto rendered or refreshed when global value changed. So need to worry about finding the components that share same value and update them manually. All are automated. All you need is to change or add values.

Here we are using create-react-app boilerplate to test our code. Plugin used is ReactN.

Plugin Used :  ReactN (npm i --save reactn)

Boilerplate used: create-react-app

What is ReactN ?

Out of the box, React’s state management is limited to a component’s scope or at the very most, a shared state that requires wiring components together. This lack of a global state is why things like Redux and various other packages exist. New on the scene is ReactN which is an extension of React that comes with state management at a global scale baked right in.

ReactN is react hook and can be used inside a React functional component, not in class component. If you want to used this react hook (reactN) inside a react class component check bottom of this article on how to use ReactN inside a react class component. Explained with example and important points break down to ordered list for easy understanding.

What is Functional Component ?

If you know what are functional components then you can skip this section. Because you can't proceed if you don't know about react functional components. Because react hooks are meant to be used with functional components not with class Components.

You can only call Hooks while React is rendering a function component.

Example react functional component

function Hello(props){
   return <div>Hello I'am {props.name} and 
            inside a fuctional component</div>
}

Example functional component in ES6

const Hello = ({name}) =>{ 
    <div>Hello {name}</div>
    }

Example Class Component

import React, { Component } from 'react';
class Hello extends Component{
   render(){
      return <div>Hello {this.props.name}</div>
   }
}

Sharing Global State among React Components

  1. npm i --save reactn
  2. create first component (ex: FirstComponent.js)
    1. Where we set value to our global state (ex: count)
  3. create second component ( ex: SecondComponent.js)
    1. Where we access global state value and check whether it automatically get updated (ex: value "count" increases or decreases)
  4. import them in App.js (main js file) and renders. (I am using create-react-app boilerplate.)
    1. For more information about create-react-app click here.

Step 1: Setting up global values before react rendering

Before you use global state you have to define them before reactDom.render function.

index.js

import { setGlobal } from 'reactn';
// Set an initial global state directly:
setGlobal({
  count: 0
});

ReactDOM.render(<App/>, document.getElementById('root'));

Let's create First Component as a react functional component since we are using react hook.
Using reactN we can change global state using 2 methods.

  1. Accessing only required Global value
    1. ex:  const [count, setCount] = useGlobal("count");
  2. Accessing all global values
    1. ex: const [ global, setGlobal ] = useGlobal();

Using First method we access only the required global state and change only that value. In second method we access all global values and can change any global value inside the react functional component.

Method 1: Accessing only required global value

Click here to download source code

FirstComponent.js

import React, { useGlobal } from "reactn";

const FirstComponent = () => {
  /**
   * @args
   *  @first  - variable name of the global state
   *  @second - function name used to change above state
   * useGlobal("value of the global state that we want")
   */
  
  const [count, setCount] = useGlobal("count");

  const increment = () => setCount(count+1)
  const decrement = () => setCount(count-1)
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => increment()}>+</button>
      <button onClick={() => decrement()}>-</button>
    </div>
  );
}

export default FirstComponent;

SecondComponent.js

import React, { useGlobal } from "reactn";

const SecondComponent = () => {
  /**
   * Get only required global state value
   */
  const [ count ] = useGlobal("count");
  
  return (
    <div>
      <h2>Second Component</h2>
      Count is :{count}
    </div>
  );
}

export default SecondComponent

Now import those components to app.js. I am not going to do that. If you want the working example you can find that at the end of this article. Once you import those two components you can see when you increase the "Count" on first component it will update the second component automatically.

Simple and easy. No framework and no need to manually render second component.

Method 2: Access all global values inside React component - ReactN

Above (method 1) you can see only the required global value is accessed. If you want to access all of the global values it is simple as above example.

Click here to download source code

FirstComponent.js

import React, { useGlobal } from "reactn";

const FirstComponent = () => {
  /**
   * @args
   *    @first - global state
   *    @second - function to change global state. 
   *    You can change global state using "useGlobal" function too. Both are covered here.
   */
  const [ global, setGlobal ] = useGlobal();
  
  /**Increasing count using setGlobal function that we defined. 
   * You can change the name of the function*/
  const increment = () => setGlobal(state => ({
    count: state.count+1
  }))

  /**Descreasing count using useGlobal */
  const decrement = useGlobal(state => ({
    count: state.count - 1
  }));

  return (
    <div>
      <p>Count: {global.count}</p>
      <button onClick={() => increment()}>+</button>
      <button onClick={() => decrement()}>-</button>
    </div>
  );
}

export default FirstComponent;

SecondComponent.js

import React, { useGlobal } from "reactn";

const SecondComponent = () => {

  /**
   * Get all global state
   */
  const [global] = useGlobal();
  
  return (
    <div>
      <h2>Second Component</h2>
      Count is :{global.count}
    </div>
  );
}

export default SecondComponent

Now import those two components and see how those components behave. Using React hook inside a class will be covered later. I am using ReactN inside a React class component.

Source Codes of ReactN Examples:

Download Method 1 Example Code: Accessing only required global state values

Download Now

Download Method 2 Example Code: Accessing all global state inside a react component.

Download Now

How to run Examples:

npm i
npm start