React state management in a web application with React Context
This post is going to explain how I use and organize state in the SplittaExpens application, an application for handling split bills
React state management
React state management is not some thing new and so React Context. State management is an important part that an app usually need to handle. We have a bunch of options for handling with state from Flux, Redux, Recoil, ... to simply React Context which is builtin in react.
In this post I will explain how I use React Context for state handling in the SplittaExpens app. In case you do not know what is SplittaExpens then it is a split bills app which can be found here https://splittaxpens.app/getting-started
State management in SplittaExpens
How state is organized
Logically the app is divided to three levels as below
[-] App
[--] Routes
[---] Pages
App level
- in app level we have AppContext which contains state and methods like load current user, notification. This means that every pages can have access to this appContext
- I like separating ui logic and business logic so I put the initialization for context at a HoC, withAppContext
in withAppContext it will
- get the authenticationState
- expose methods for update profile
Routes level
- nothing special here, it just contains react-router-dom components.
Pages level
- I consider a page is basically a screen where users can reach by a url.
- at this level I create different contexts for every page.
- at page level code can have access to the corresponding context or the AppContext
- My favorite setup is to put the initialization of context at a HoC and I usually do not render the main component until states needed are ready.
the HoC will do
- load corresponding data from server via Repository and update the holding state
- expose methods for updating both server and client state and also loading state
Summary
- React Context is easy to use and when we use it the right way then it will help us to reduce props transfering between components.
- The SplittaExpens is relatively small so it shows no big challenges. It will have more challenges when working with complex components that contains many information and interactions.
- The next post I will talk about how I organized state in a cms which is more complex
the original post is found here https://www.hittaducmai.se/blogs/react-state-management-in-a-web-application-with-react-context