Two Patterns with React Context<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Two Patterns with React Context

Posted on: August 27, 2021

For some reason, I am always copying a previous React Context before creating a new one. I recently realized that I was copying two different patterns. In this article, I'll expose the two patterns.

Class Pattern with React Hook

The first pattern is succinct but requires relying on a class. First, the logic of the shared code, the context code, is inside a class. It means that every value you want to share across your component via the context or any functions is stored in a class. So, three steps are required. The first one is to create a class.

1export class MySharedLogic {
2 public message: string;
3 public setmessage(s){this.message=s;}

The second is to create the context.

1export const MySharedLogicContext = createContext<MySharedLogic | undefined>(undefined);

This is to place the context in the React component tree. Usually, this is very high, next to the start of the application.

1return <div>
2 <MySharedLogicContext.Provider value={instanceOfMySharedLogicClassHere}>
3 <div>
4 ...
5 </div>
6 </MySharedLogicContext.Provider>

From that point, any component under the context from the previous block of code can use the Read hook useContext to get access to everything from the class MySharedLogic.

1const fromContext = useContext(MySharedLogicContext);

Object Pattern with React Hook

The second pattern is a little bit more verbose but avoid using a class. What we need to do is to define an interface with the contract of the shared logic.

1export interface MySharedLogic {
2 message: string;
3 setMessage: (m: string) => void;

Then, we create the context with placeholder value or the actual value if we are able to provide it at this time. It can happen that the logic or information is only available at runtime, hence defined later. In the case that it is defined later, the code would look l like the following. To avoid having these empty functions, it is possible to allow the context to be MySharedLogic | undefined instead of only MySharedLogic.

1export const MySharedLogicContext = createContext<MySharedLogic>({
2 message: "",
3 setMessage: () => {
4 /*Implementation later in a React Hook*/
5 }

The next step is to put the context in the React DOM tree. Similar to the previous pattern but at that time we can define the logic. To keep the code cleaner, I usually wrap the portion into a function so it looks like:

1export interface MySharedLogicContextProviderProps {
2 children: ReactElement;
4export const MySharedLogicContextProvider = (props: MySharedLogicContextProps): ReactElement => {
5 const [message, setMessage] = useState<string>("");
6 return (
7 <MySharedLogicContext.Provider
8 value={{
9 setMessage: (m: string) => {
10 setMessage(m);
11 },
12 message: message,
13 }}
14 >
15 {props.children}
16 </AppMessageContext.Provider>
17 );

The provider in the tree:

1return <div>
2 <MySharedLogicContextProvider>
3 <div>
4 ...
5 </div>
6 </MySharedLogicContextProvider>

The Differences

The decision between the pattern is a matter of the role of the context. The class has less boilerplate to configure reducing the cognitive load to understand each part. However, if the role of the context is to share a user interface feature like having a global confirmation or error popup will get more complex. The class encapsulates the JavaScript/TypeScript code outside the lifecycle of React.

On the contrary, with more code without the class, the object pattern with the provider React Hook function gives you direct access to any user interface code. You might argue that with the class, it is possible to also access the user interface by creating a wrapper, similar to the object, instead of directly using the MySharedLogicContext.Provider. The observation is valid. However, the emphasis of these two patterns is that one relies on a class, the second not, and that without relying on a class, you must store the values of the context somewhere. In this article, I am storing the value inside a React state (useState). Another option could be to use store the values directly into the ECMAScript module where the createContext is called.

In either case, you have all the flexibility you desire and you will not be constrained. A heuristic I found is that if you need to have a context with reactive content, for example, a message that displays on the screen, the object pattern is ideal: because the data is stored in a state, the consumer with useContext will receive the new value and the one responsible to display the message in the user interface can react naturally. The class pattern is less prone to reactivity since the value will change but React will not render a change. Hence, I found using the class pattern in scenarios where I am pushing changes. For example, a context that checks the user's permission where the context was filled at the beginning of the application's boot process and then kept the value in the context to be consumed as needed.