Developer way

How to write performant React apps with Context

Nadia Makarevich

Nadia Makarevich

Feb 7, 2022

Nadia MakarevichNadia Makarevich

It’s impossible to have a conversation on how to write performant React code without having an article or two on Context. And it’s such a controversial topic! There are so many prejudices and rumours surrounding it. Context is evil! React re-renders everything for no reason when you use Context! Sometimes I have a feeling that developers treat Context like it’s a magic gremlin, that randomly and spontaneously re-renders the entire app for its own amusement.

In this article I do not intend to convince anyone that we should ditch our beloved state management libraries in favour of Context. They exist for a reason. The main goal here is to de-mystify Context and provide a few interesting coding patterns, that could help minimise Context-related re-renders and improve your React apps performance. And as a nice bonus, the code will look cleaner and more understandable as a result.

Let’s start the investigation with implementing some real-life app, and see where this will take us.

Let’s implement a form in React

Our form is going to be quite complicated, it would consist, to begin with, from:

  • a “Personal info“ section, where people can set some personal information, i.e name, email, etc
  • a “Value calculation“ section where people can set their currency preferences, their preferred discount, add some coupons, etc
  • the selected discount should be highlighted in the Personal section in a form of an emoji (don’t ask, the designer has a weird sense of humour)
  • an “Actions” section with action buttons (i.e. “Save”, “Reset”, etc)

The “design” looks like this:

To make things more interesting, we’re also going to pretend that “select country” and “dragging bar” components are “external” libraries that we installed as a package. So we can only use them through API, but have no influence on what’s inside. And we’re going to use the “slow” version of the countries select, that we implemented in the previous performance investigation.

Now it’s time to write some code. Let’s start with the components structure of the app. I know this form will quickly become quite complicated, so I want to separate it into smaller, more contained components right away.

At the root I’ll have my main Form component, which will render the three required sections:

1const Form = () => {
2 return (
3 <>
4 <PersonalInfoSection />
5 <ValueCalculationsSection />
6 <ActionsSection />
7 </>
8 );
9};

“Personal info” section will then render three more components: the discount emoji, input for the name and countries select

1const PersonalInfoSection = () => {
2 return (
3 <Section title="Personal information">
4 <DiscountSituation />
5 <NameFormComponent />
6 <SelectCountryFormComponent />
7 </Section>
8 );
9};

All three of them will contain the actual logic of those components (the code of them will be below), and the Section just encapsulates some styles.

“Value calculation” section will have just one component (for now), the discount bar:

1const ValueCalculationSection = () => {
2 return (
3 <Section title="Value calculation">
4 <DiscountFormComponent />
5 </Section>
6 );
7};

And “Actions” section will have just one button for now as well: the save button with onSave callback.

1const ActionsSection = ({ onSave }: { onSave: () => void }) => {
2 return (
3 <Section title="Actions">
4 <button onClick={onClick}>Save form</button>
5 </Section>
6 );
7};

Now the interesting part: we need to make this form interactive. Considering that we have a single “Save” button for the entire form, and different sections would need data from other sections, the natural place for the state management is at the root, in the Form component. We’ll have 3 pieces of data there: Name, Country and Discount, a way to set all three of them, and a way to “save” it:

1type State = {
2 name: string;
3 country: Country;
4 discount: number;
5};
6
7const Form = () => {
8 const [state, setState] = useState<State>(defaultState as State);
9
10 const onSave = () => {
11 // send the request to the backend here
12 };
13
14 const onDiscountChange = (discount: number) => {
15 setState({ ...state, discount });
16 };
17
18 const onNameChange = (name: string) => {
19 setState({ ...state, name });
20 };
21
22 const onCountryChange = (country: Country) => {
23 setState({ ...state, country });
24 };
25
26 // the rest as before
27};

And now we need to pass the relevant data and callbacks to the components that need it. In our PersonalInfoSection:

  • the DiscountSituation component should be able to show the emoji based on discount value.
  • the NameFormComponent should be able to control name value
  • the SelectCountryFormComponent should be able to set the selected country

Considering that those components are not rendered in Form directly, but are children of PersonalInfoSection, time to do some prop drilling 😊

DiscountSituation will accept discount as a prop:

1export const DiscountSituation = ({ discount }: { discount: number }) => {
2 // some code to calculate the situation based on discount
3 const discountSituation = ...;
4 return <div>Your discount situation: {discountSituation}</div>;
5};

NameFormComponent will accept name and onChange callback:

1export const NameFormComponent = ({ onChange, name }: { onChange: (val: string) => void; name: string }) => {
2 return (
3 <div>
4 Type your name here: <br />
5 <input onChange={() => onChange(e.target.value)} value={name} />
6 </div>
7 );
8};

SelectCountryFormComponent will accept onChange callback:

1export const SelectCountryFormComponent = ({ onChange }: { onChange: (country: Country) => void }) => {
2 return <SelectCountry onChange={onChange} />;
3};

And our PersonalInfoSection would have to pass all of them from its parent Form component to its children:

1export const PersonalInfoSection = ({
2 onNameChange,
3 onCountryChange,
4 discount,
5 name,
6}: {
7 onNameChange: (name: string) => void;
8 onCountryChange: (name: Country) => void;
9 discount: number;
10 name: string;
11}) => {
12 return (
13 <Section title="Personal information">
14 <DiscountSituation discount={discount} />
15 <NameFormComponent onChange={onNameChange} name={name} />
16 <SelectCountryFormComponent onChange={onCountryChange} />
17 </Section>
18 );
19};

And the same story with ValueCalculationSection: it needs to pass onDiscountChange and discount value from Form component to its child:

1export const ValueCalculationsSection = ({ onDiscountChange }: { onDiscountChange: (val: number) => void }) => {
2 console.info('ValueCalculationsSection render');
3 return (
4 <Section title="Value calculation">
5 <DiscountFormComponent onDiscountChange={onDiscountChange} />
6 </Section>
7 );
8};

And the DiscountFormComponent just uses the “external” library DraggingBar to render the bar and catch the changes via the callback it gives:

1export const DiscountFormComponent = ({ onDiscountChange }: { onDiscountChange: (value: number) => void }) => {
2 console.info('DiscountFormComponent render');
3 return (
4 <div>
5 Please select your discount here: <br />
6 <DraggingBar onChange={(value: number) => onDiscountChange(value)} />
7 </div>
8 );
9};

And, the render of our Form component would look like this:

1const Form = () => {
2 return (
3 <div>
4 <PersonalInfoSection onNameChange={onNameChange} onCountryChange={onCountryChange} discount={state.discount} name={state.name} />
5 <ValueCalculationsSection onDiscountChange={onDiscountChange} />
6 <ActionsSection onSave={onSave} />
7 </div>
8 );
9};

Quite a bit of code, but finally done 😅 Want to take a look at the result? See the codesandbox.

Unfortunately, the result is much worst than you’d expect from a composition of a few components and a simple state 😕 Try to type your name in the input, or drag the blue bar - both of them are lagging even on a fast laptop. With CPU throttling they are basically unusable. So, what happened?

The form performance investigation

First of all, let’s take a look at the console output there. If I type a single key in the Name input, I’ll see:

1Form render
2PersonalInfoSection render
3Section render
4Discount situation render
5NameFormComponent render
6SelectCountryFormComponent render
7ValueCalculationsSection render
8Section render
9DiscountFormComponent render
10ActionsSection render
11Section render

Every single component in our form re-renders on every keystroke! And the same situation is with the dragging - on every mouse move the entire form and all its components re-renders themselves. And we already know, that our SelectCountryFormComponent is very slow, and there is nothing we can do with its performance. So the only thing that we can do here, is to make sure it doesn’t re-render on every keypress or mouse move.

And, as we know, components will re-render when:

  • state of a component changed
  • parent component re-renders

And this is exactly what is happening here: when the value in an input changes, we propagate this value up to the root Form component through our chain of callbacks, where we change the root state, which triggers re-render of the Form component, which then cascades down to every child and child of a child of this component (i.e. all of them).

To fix it, we could, of course, sprinkle some useMemo and useCallback in strategic places and call it a day. But that just brushes the problem under the rug, not actually solving it. When in the future we introduce another slow component, the story will repeat itself. Not to mention that it will make the code much more complicated and harder to maintain. In the ideal world, when I type something in the Name component, I want only the NameFormComponent and components that actually use the name value to re-render, the rest should just sit idle there and wait for their turn to be interactive.

And React actually gives us a perfect tool to do that - Context!

Adding Context to the form

As per React docs, context provides a way to pass data through the component tree without having to pass props down manually at every level. If, for example, we extract our Form state into Context, we can get rid of all the props we’ve been passing through intermediate sections like PersonalInfoSection and use state directly in the NameFormComponent and DiscountFormComponent. The data flow then would look something like this:

To achieve this, first we’re creating the Context itself, which will have our state and the API to manage this state (i.e. our callbacks):

1type State = {
2 name: string;
3 country: Country;
4 discount: number;
5};
6
7type Context = {
8 state: State;
9 onNameChange: (name: string) => void;
10 onCountryChange: (name: Country) => void;
11 onDiscountChange: (price: number) => void;
12 onSave: () => void;
13};
14
15const FormContext = createContext<Context>({} as Context);

Then we should move all the state logic, that we had in Form, in the FormDataProvider component, and attach the state and callbacks to the newly created Context:

1export const FormDataProvider = ({ children }: { children: ReactNode }) => {
2 const [state, setState] = useState<State>({} as State);
3
4 const value = useMemo(() => {
5 const onSave = () => {
6 // send the request to the backend here
7 };
8
9 const onDiscountChange = (discount: number) => {
10 setState({ ...state, discount });
11 };
12
13 const onNameChange = (name: string) => {
14 setState({ ...state, name });
15 };
16
17 const onCountryChange = (country: Country) => {
18 setState({ ...state, country });
19 };
20
21 return {
22 state,
23 onSave,
24 onDiscountChange,
25 onNameChange,
26 onCountryChange,
27 };
28 }, [state]);
29
30 return <FormContext.Provider value={value}>{children}</FormContext.Provider>;
31};

Then expose the hook for other components to use this Context without accessing it directly:

1export const useFormState = () => useContext(FormContext);

And wrap our Form component into the FormDataProvider:

1export default function App() {
2 return (
3 <FormDataProvider>
4 <Form />
5 </FormDataProvider>
6 );
7}

After that, we can get rid of all the props throughout the app, and use the required data and callbacks directly in the components where it’s needed via useFormState hook.

For example, our root Form component will turn into just this:

1const Form = () => {
2 // no more props anywhere!
3 return (
4 <div className="App">
5 <PersonalInfoSection />
6 <ValueCalculationsSection />
7 <ActionsSection />
8 </div>
9 );
10};

And NameFormComponent will be able to access all the data like this:

1export const NameFormComponent = () => {
2 // accessing the data directly right where it's needed!
3 const { onNameChange, state } = useFormState();
4
5 const onValueChange = (e: ChangeEvent<HTMLInputElement>) => {
6 onNameChange(e.target.value);
7 };
8
9 return (
10 <div>
11 Type your name here: <br />
12 <input onChange={onValueChange} value={state.name} />
13 </div>
14 );
15};

Take a look at the full code in this codesandbox. Don’t forget to appreciate how clean it looks now when there is no more mess of props everywhere!

What about the performance of the new form?

From the performance perspective we’re still not there yet: typing the name and dragging the bar is still lagging. But if I start typing in the NameFormComponent, in the console I will now see this:

1Discount situation render
2NameFormComponent render
3SelectCountryFormComponent render
4DiscountFormComponent render
5ActionsSection render
6Section render

Half of the components now don’t re-render, including our parent Form component. This is happening because of how Context works: when a Context value changes, every consumer of this context will re-render, regardless of whether they use the changed value or not. But also, those components that are bypassed by Context won’t be re-rendering at all. Our re-renders flow now looks like this:

And now, if we look closely at our components implementation, in particular SelectCountryComponent, which is the wrapper around the slow “external” component, we’ll see that it doesn’t actually use the state itself. All it needs is the onCountryChange callback:

1export const SelectCountryFormComponent = () => {
2 const { onCountryChange } = useFormState();
3 console.info('SelectCountryFormComponent render');
4
5 return <SelectCountry onChange={onCountryChange} />;
6};

And this gives us an opportunity to try out a really cool trick: we can split the state part and the API part under our FormDataProvider.

Splitting the state and the API

Basically, what we want to do here is to decompose our “monolith” state into two “microstates” 😅.

Instead of one context that has everything we’d need 2 contexts, one for data, one for API:

1type State = {
2 name: string;
3 country: Country;
4 discount: number;
5};
6
7type API = {
8 onNameChange: (name: string) => void;
9 onCountryChange: (name: Country) => void;
10 onDiscountChange: (price: number) => void;
11 onSave: () => void;
12};
13
14const FormDataContext = createContext<State>({} as State);
15const FormAPIContext = createContext<API>({} as API);

Instead of one context provider in our FormDataProvider component, we’d again have two, where we’d pass our state directly to the FormDataContext.Provider:

1const FormDataProvider = () => {
2 // state logic
3
4 return (
5 <FormAPIContext.Provider value={api}>
6 <FormDataContext.Provider value={state}>{children}</FormDataContext.Provider>
7 </FormAPIContext.Provider>
8 );
9};

And now the most interesting part, the api value.

If we just leave it as it was before, the whole “decomposition” idea is not going to work because we still would have to rely on the state as a dependency in the useMemo hook:

1const api = useMemo(() => {
2 const onDiscountChange = (discount: number) => {
3 // this is why we still need state here - in order to update it
4 setState({ ...state, discount });
5 };
6
7 // all other callbacks
8
9 return { onSave, onDiscountChange, onNameChange, onCountryChange };
10 // still have state as a dependency
11}, [state]);

This will result in the api value changing with every state update, which would lead to the FormAPIContext triggering re-renders on every state update, which would make our split useless. We want our api to stay constant regardless of the state, so that consumers of this provider don't re-render.

Fortunately, there is another neat trick that we can apply here: we can extract our state into a reducer and instead of calling setState in the callback we would just trigger a reducer action.

First, create actions and reducer itself:

1type Actions =
2 | { type: 'updateName'; name: string }
3 | { type: 'updateCountry'; country: Country }
4 | { type: 'updateDiscount'; discount: number };
5
6const reducer = (state: State, action: Actions): State => {
7 switch (action.type) {
8 case 'updateName':
9 return { ...state, name: action.name };
10 case 'updateDiscount':
11 return { ...state, discount: action.discount };
12 case 'updateCountry':
13 return { ...state, country: action.country };
14 }
15};

Use reducer instead of useState:

1export const FormProvider = ({ children }: { children: ReactNode }) => {
2 const [state, dispatch] = useReducer(reducer, {} as State);
3 // ...
4};

And migrate our api to dispatch instead of setState:

1const api = useMemo(() => {
2 const onSave = () => {
3 // send the request to the backend here
4 };
5
6 const onDiscountChange = (discount: number) => {
7 dispatch({ type: 'updateDiscount', discount });
8 };
9
10 const onNameChange = (name: string) => {
11 dispatch({ type: 'updateName', name });
12 };
13
14 const onCountryChange = (country: Country) => {
15 dispatch({ type: 'updateCountry', country });
16 };
17
18 return { onSave, onDiscountChange, onNameChange, onCountryChange };
19 // no more dependency on state! The api value will stay the same
20}, []);

And the final step: don’t forget to migrate all the components that used useFormState to useFormData and useFormAPI. For example, our SelectCountryFormComponent will use onCountryChange from the useFormAPI hook, and will never re-render on the state change.

1export const SelectCountryFormComponent = () => {
2 const { onCountryChange } = useFormAPI();
3
4 return <SelectCountry onChange={onCountryChange} />;
5};

Take a look at the full implementation in this codesandbox. The typing and dragging bar are blazing fast now, and the only console output we’d see when we type something is this:

1Discount situation render
2NameFormComponent render

Only two components, since only those two use the actual state data. 🎉

Splitting state even further

Now, people with good design eyes or just careful readers might notice that I cheated a little bit. We don’t pass the selected country to our “external” SelectCountry component, and it's stuck on the very first item in the list. In reality, the selected “lilac” color should move to the country you click on. And the component actually allows us to pass it via activeCountry. Technically, I can do it as simple as that:

1export const SelectCountryFormComponent = () => {
2 const { onCountryChange } = useFormAPI();
3 const { country } = useFormData();
4
5 return <SelectCountry onChange={onCountryChange} activeCountry={country} />;
6};

There is one problem with it though - as soon as I use useFormData hook in a component, it will start re-rendering with the state changes, same as NameFormComponent. Which in our case means we’ll be back to the laggy experience on typing and dragging.

But now, since we already know how to split the data between different providers, nothing stops us from taking this to the next level and just splitting the rest of the state as well. Moar providers! 😅

Instead of one unified context for State we’ll have three now:

1const FormNameContext = createContext<State['name']>({} as State['name']);
2const FormCountryContext = createContext<State['country']>({} as State['country']);
3const FormDiscountContext = createContext<State['discount']>({} as State['discount']);

Three state providers:

1<FormAPIContext.Provider value={api}>
2 <FormNameContext.Provider value={state.name}>
3 <FormCountryContext.Provider value={state.country}>
4 <FormDiscountContext.Provider value={state.discount}>{children}</FormDiscountContext.Provider>
5 </FormCountryContext.Provider>
6 </FormNameContext.Provider>
7</FormAPIContext.Provider>

And three hooks to use the state:

1export const useFormName = () => useContext(FormNameContext);
2export const useFormCountry = () => useContext(FormCountryContext);
3export const useFormDiscount = () => useContext(FormDiscountContext);

And now in our SelectCountryFormComponent we can use useFormCountry hook, and it will not be re-rendering on any changes other than country itself:

1export const SelectCountryFormComponent = () => {
2 const { onCountryChange } = useFormAPI();
3 const country = useFormCountry();
4
5 return <SelectCountry onChange={onCountryChange} activeCountry={country} />;
6};

Check this out in codesandbox: it’s still fast, and country is selectable. And the only thing we’ll see in console output when we type something in the name input is:

1NameFormComponent render

Bonus: external state management

Now, the question of whether this form’s state should’ve been implemented with some state management library right away might cross some of your minds. And you’re maybe right. After all, if we look closely at the code, we just re-invented the wheel and implemented a rudimentary state management library, with selectors-like functionality for the state and separate actions to change that state.

But now you have a choice. Context is not a mystery anymore, with those techniques you can easily write performant apps with just pure Context if there is a need, and if you want to transition to any other framework, you can do it with minimal changes to the code. State management framework doesn’t really matter when you design your apps with Context in mind.

We might as well move it to the good old Redux right now. The only things we’d need to do are: get rid of Context and Providers, convert React reducer to Redux store, and convert our hooks to use Redux selectors and dispatch.

1const store = createStore((state = {}, action) => {
2 switch (action.type) {
3 case 'updateName':
4 return { ...state, name: action.payload };
5 case 'updateCountry':
6 return { ...state, country: action.payload };
7 case 'updateDiscount':
8 return { ...state, discount: action.payload };
9 default:
10 return state;
11 }
12});
13
14export const FormDataProvider = ({ children }: { children: ReactNode }) => {
15 return <Provider store={store}>{children}</Provider>;
16};
17
18export const useFormDiscount = () => useSelector((state) => state.discount);
19export const useFormCountry = () => useSelector((state) => state.country);
20export const useFormName = () => useSelector((state) => state.name);
21
22export const useFormAPI = () => {
23 const dispatch = useDispatch();
24
25 return {
26 onCountryChange: (value) => {
27 dispatch({ type: 'updateCountry', payload: value });
28 },
29 onDiscountChange: (value) => dispatch({ type: 'updateDiscount', payload: value }),
30 onNameChange: (value) => dispatch({ type: 'updateName', payload: value }),
31 onSave: () => {},
32 };
33};

Everything else stays the same and works exactly as we designed. See the codesandbox.

That is all for today, hope now Context is not the source of mysterious spontaneous re-renders in your app, but a solid tool in your arsenal of writing performant React code ✌🏼

Share on:Share "How to write performant React apps with Context" on TwitterShare "How to write performant React apps with Context" on LinkedInShare "How to write performant React apps with Context" on Reddit
Get the latest content by email
    No spam or ads. Unsubscribe at any time.
    © Developer Way 2021