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.
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
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
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
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
userPostsProvider, which are the only two things we need:
Find the top most component that is a parent to both
UserPosts (see diagram above). In this case, it is the
Layout component, and wrap it with
userPostsProvider (so its children have access to the state):
AddUserPosts has a button that adds posts. We can use
useContext like so:
Same thing goes for
UserPosts, we also use
UserPostsContext to display
And we are done! Any time a post is added in
AddUserPost it automatically updates
UserPosts to reflect that.
To create global state you have to follow those steps:
createGlobalStatewith the default value and export the tuples
- Wrap the topmost component, that is a parent of the components that need access to the data, with the
- Use the context returned by
useContextin a component you need to get and modify the state.