Simple Global State Management – Not redux

This is for the people who have simple knowledge on react application development. Because this tutorial mainly focused on global state management in react.

As you know that there is no in built way to share global state among react component. Each state is unique to each react component and disappear when that component get unmounted. So in order to have global shared state or store you may need to have another framework built in to react. Learning those frameworks are tricky or hard for some people and beginners. 

One of the best framework used was Redux. There are more like flux and etc.  Learning redux is so hard and require some skills and learning for new comers. Is their any other solution for this. You are here finding some simple easy to learn method to manage global state among all react component without needing to learn those hard JavaScript frameworks. Yeah, there is a way. Simple and easy. It is called ReactN. 

What is reactN ?

ReactN is a simple react based NPM package that allows react developers to maintain single global state. Just like Redux you can add, delete, update and read from global state using ReactN.

You may need only few hours to learn this package. Some may require only few minutes. With compared to Redux it is lots of time saving for your project. So why all the people are not using ReactN. It is because ReactN is good for simple and small react applications. Not for large and expanding react projects. You can even use this on redux based projects too. It is based on you. You can use this with any react based boilerplate without needing to changing the structure. That’s why this npm package is so popular and important.

ReactN is react hook. Before using this you may need to know about react hooks and its applications. You can use React hooks with functional components only. Not with Class components.

Below shows a example react functional component.

Why ReactN ?

  • As you know if you want to share state among react components you need to pass those values from one components to other. With ReactN no need to do that.
  • If you are using same value in many react components and need to update it when that value it may be so hard. For example users name on header need to be change when editing profile information. Instead of manually updating those components you can use reactN to automatically update them. 
  • No need to keep track and update components that use global state. ReactN will automatically update each and every component when global state changes.

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

What ever, let dig deep and learn how to use those features. For your convenience I am going to create simple counting app. Using only one global value “count” and access that value in another component and update it using another component to see how that variable behave.

Step 1: Installing required Packages

What ever the react boilerplate you are using, we need only one package. Here I am using create-react-app boilerplate. Let’s install reactN package.

npm install --save reactn

Step 2: Initialize react global state.

This is like creating database and its table. First of all let’s initialize react global state. Make sure you have to initialize it before react dom render (ReactDom.render) function.  In create-react-app, it is in index.js.

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

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

Step 3: Access global value and update it.

After we initialize our global state, lets access that value and change its value. Here I am creating a new react component called “FirstComponent”. Then get initialized react global value and update it.

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;

Import this component to your main react app.js and see how this work.

Step 4: See components auto updates with global state

Above we have access the global value “count” and change its value. Now we are only accessing that global value only and see whether that value get updated when global value changes in SecondComponent (updating global state occur FirstComponent)

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

Import this SecondComponent to app.js and see who SecondComponent behave when global state changes using FirstComponent.

Leave a Reply

avatar
  Subscribe  
Notify of