Understanding patterns and anti-patterns in React
Recently, while working with our large React app codebase, we came to a screeching halt against three categories of bugs — they were not compile-time or run-time errors but unexpected code behaviors.
- A component does not update upon a user event.
- A component updates partially upon a user event.
- A component renders unexpectedly.
Our first instinct was of course to “battle evil wherever we could find it.”
However, even after a litany of print statements, the bugs remained hard to trace. It is then that we realized that certain parts of our code could be considered anti-patterns.
So we spent a lot of time understanding and characterizing them as such to ensure that we avoid these mistakes in the future.
This article is an attempt at explaining those discoveries.
In this article, a React code qualifies as a good pattern if:
- The component is reusable.
- The code is easier to review and debug.
Note that the code is still considered a pattern if we wrote more lines of code or we (expectedly) introduced a few extra renders in order to achieve the above objectives.
Why do even experienced developers fall into the trap of anti-patterns?
- The React code looks surprisingly similar when it follows a pattern vs. the time when it follows an anti-pattern.
- The pattern seems so obvious that it gets ignored.
Hint #1: Hook without a dependency array
In React, different pieces of code are linked to each other by dependencies. These pieces of interdependent code together keep the application state in its desired form. Therefore, if we write a piece of code in React that does not have a dependency, there is a high chance that it will result in bugs.
Hence, be careful when you are using hooks such as
useRef etc. because they do not take dependencies arrays.
Hint #2: Nesting over composition
There are two mechanisms using which React components are arranged:
- Composition: All children have the same data
- Nesting: Each child can have different data
Let us imagine a scenario where we observe that there is a bug in “Child 3.”
If we had arranged the components using composition, we would not have to look into the code of “Child 1” and “Child 2” because all are independent. Hence, the time complexity of debugging would be
However, if we had arranged the components using nesting, we would have to check all the children before “Child 3” to figure out the source of the bug. In this case, the time complexity of debugging would be
O (n) where
n is the number of children above “Child 3.”
Hence, we can conclude that nesting often makes the debugging process harder than composition does.
Now, let us consider an app to demonstrate different patterns and anti-patterns.
Desired behavior of the app
When an article is clicked in the left navigation menu, it opens on the right. This is followed by two actions:
- Computation: The total character count of the article is calculated as
(num_chars(title) + num_chars(text)and displayed.
- Network request: Based on the total character count of the article, an emoji is fetched via a network request and displayed. As the character count increases, the emoji changes from sad to happy.
Building the app
We will get to the correct way of building this app in four steps:
- Incorrect: The app does not work as expected — neither computation nor network request is triggered when a new article is selected.
- Partially correct: The app works as expected but a flickering effect is observed when a new article is selected.
- Correct but suboptimal: The app works as expected without DOM flickers but makes unnecessary network requests.
- Correct and optimal: The app works as expected without DOM flickers and unnecessary network requests.
Below is an embedded sandbox of this app. Review each approach by clicking on the corresponding option in the top navigation bar. Check how the app performs when an article is clicked in the left navigation menu.
You can open the above sandbox by clicking on the button at the bottom right corner.
src/pages directory has pages mapped to each step. The file for each page in
src/pages contain a
ArticleContent component. The code under discussion is inside this
Let us now review the anti-patterns and patterns followed in the above four approaches.
Anti-Pattern #1: Props or context as initial state
In the incorrect approach,
context has been used as an initial value for
useRef. In line 27, we can see that the average length has been calculated and stored as a state.
This anti-pattern is the reason why neither computation nor network request is triggered when a new article is selected.
Anti-Pattern #2: Destroy and Recreate
Let us make amends for our incorrect approach by using the ‘Destroy and Recreate’ anti-pattern.
Destroying a functional component refers to destroying all the hooks and the states created during the first function call. Recreating refers to calling the function again as if it had been never called before.
Note that a parent component can use the
key prop to destroy the component and recreate it every time the
key changes. Yes, you read it right — you can use keys outside loops.
Specifically, we implement ‘Destroy and Recreate’ anti-pattern by using the
key prop while rendering the child component
ArticleContent of the parent component
RecreateDoc in the
RecreateDoc.tsx file (line 89).
The app works as expected but a flickering effect is observed when a new article is selected. Hence, this anti-pattern results in a partially correct output.
Pattern #1: Internal State in JSX
Instead of using the ‘Destroy and Recreate’ anti-pattern, in this ‘correct but suboptimal’ approach, we will use ‘rerendering.’
Rerendering refers to calling the react functional component again with the hooks intact across function calls. Note that in ‘Destroy and Recreate,’ all the hooks are destroyed first and then recreated from scratch.
To implement ‘reendering,’
useState will be used in tandem. The initial value for the
useState can be set to
undefined and an actual value will be computed and assigned to it once
useEffect has run. In this pattern, we are circumventing the lack of dependency array in
useState by using
Specifically, notice how we have moved the total character count computation into JSX (line 50) and we are using
props (line 41) as a dependency in the
useEffect (line 31).
Using this pattern, the flickering effect has been avoided but a network request is made to fetch emojis whenever props change. So, even if there is no change in character count, an unnecessary request is made to fetch the same emoji.
Pattern #2: Props as a dependency in useMemo
Let us do it correctly as well as optimally this time. It all started with Anti-Pattern #1:
context as the initial state.
We can fix this by using
props as a dependency in
useMemo. By moving the total character count computation to
useMemo hook, we are able to prevent network requests to fetch emojis unless the average length has changed.
In this article, we discussed that using
context as initial state and ‘Destroy and Recreate’ are anti-patterns while using internal state in JSX and
props as a dependency in
useMemo are good patterns. We also that we should be intelligent when learned we are using hooks without a dependency array and nesting for arranging React components.