Create global state in React as simply as local state

In this article, we will show you how to create global state using createGlobalState, a function we built. If you are interested in how this function is implemented in more detail go to this article.

Intro

In some cases, two components that are not located close to each other in your react component tree need to share and modify data. For example Layout and UserPosts:

This component tree is simple enough to pass components down via props, but what if the components are not directly connected in a straight line? Like the SidePanel and UserPosts:

Redux is a possible fix to this problem but it has plenty of boilerplate and has a steep learning curve especially when not familiar with functional programming. In this article, we discuss how to implement a global state that can be both shared and modified.

Create Global State

Create a new file named globalState.tsx and copy the code below (implementation details can be found here):

The code above creates a context and a context provider wrapper that lets us create a state object that can be modified and shared.

Let’s say you want to modify user posts in one part of your app and you want to display them in another. Here is a react component tree example:

First, we need a new file to store the global state. Let’s call it userPostsState.ts. To create a state, we call createGlobalState which returns a pair. The first value is a react context (which we can use in a component by calling useContext(...)) and the second value is a context provider which is used to wrap a react component, in this case the Layoutcomponent. createGlobalState takes in a type (in brackets) and a default value, in this case the type is a UserPostsModel array and the default value is an empty array. Export both UserPostsContext and userPostsProvider, which are the only two things we need:

Find the top most component that is a parent to both AddUserPost and UserPosts (see diagram above). In this case, it is the Layout component, and wrap it withuserPostsProvider (so its children have access to the state):

The component AddUserPosts has a button that adds posts. We can use UserPostsContext with useContext like so:

Same thing goes for UserPosts, we also use UserPostsContext to display posts:

And we are done! Any time a post is added in AddUserPost it automatically updates UserPosts to reflect that.

Summary

To create global state you have to follow those steps:

  1. Use createGlobalState with the default value and export the tuples
  2. Wrap the topmost component, that is a parent of the components that need access to the data, with the provider
  3. Use the context returned by createGlobalState with useContext in a component you need to get and modify the state.