React isn’t just JSX and a few hooks.
Prakhar Tandon
Posted on January 26, 2024
React is itself an ecosystem, a field of study right now. You can dive deeper to quench your thirst for knowledge to develop even more compelling and scalable applications. (Even Batman uses it)
In this series of articles, we’ll discuss some crucial, difficult yet ignored parts of React. [This is the first part, will continue this series.]
I used to think “I know React”. But after I started diving into this ocean, I don’t believe that anymore. I have gained much knowledge, but the React ecosystem is forever evolving, so you need to keep learning. Throughout all the articles, I’ll be adding links to some great authors and their writings about certain topics that I read & learned from. I’m not an expert, just trying to do better.
The “Key” Warning.
Let’s start with something super simple and common, the Map method. We all have used it to iterate over an object to render something to the screen in JSX. And we all have faced that little “key” warning but ignored it.
React uses something called the “Diffing Algorithm” to reconcile the DOM. When the state of a component changes, React creates a new virtual DOM and compares it with the current DOM. This comparison process, known as “diffing,” allows React to identify the minimum number of operations needed to update the DOM.
Read More about Diffing in this fantastic article from Peeyush Agarwal. [Recommended]
Understanding the Diffing Algorithm in React.js
So, React uses this “key” prop to differentiate between elements rendered using a “map”. If keys aren’t provided, the algorithm will have to re-render all map elements if anything is updated.
By default, React uses the index
as the key, which most new devs do, as in the example below.
import React from 'react';
const ToolsList = () => {
const [tools, setTools] = React.useState(["Dualite", "Slack", "Zoom", "Locofy"]);
return (
<ul>
{tools.map((tool, index) => (
<li key={index}>{tool}</li>
))}
</ul>
);
};
export default ToolsList;
In this example, we are mapping over the tools
state, and for each tool, we're returning a list item. We're not using any keys. But there’s a big problem.
So, if any new element is added to the beginning of the tools state, the component will re-render, including all the JSX. Now React makes a new copy of the latest VDOM and compares it to existing DOM and finds out what changes are there. Then it just updates the parts that are changed.
But, since we added to the beginning, all the indices will change and React will consider them all as new/changed elements, hence all will be re-rendered, which isn’t good.
Some people add a random value using Math.random()
which is even worse. On every re-render, that value will be recalculated, resulting in a new value every time, hence re-render.
Let’s summarise what we’ve gathered so far.
- Key props are important
- The key should be some value that is unique to the rendered element.
- The key value should be consistent across re-renders.
This leads us to the solution, using a consistent and unique-to-element value as the key. That can mostly be some element ID you have in your data or some content from the rendered element.
import React from 'react';
const ToolsList = () => {
const [tools, setTools] = React.useState([{id: 1, name: "Dualite"}]);
return (
<ul>
{tools.map((tool) => (
<li key={tool.id}>{tool.name}</li>
))}
</ul>
);
};
export default ToolsList;
This works perfectly.
The Purity in React.
React promotes the concept of immutability and purity, meaning your functions should always produce the same output for a given input, and they should not have side effects such as modifying variables outside their scope or some variable that existed before this component’s rendering.
This is crucial for better predictability and maintainability of your React applications. This is a concept from JavaScript functions, but React components are nothing but functions that return some JSX.
Consider the following example:
let outsideVariable = 10;
function Comp() {
outsideVariable = 20;
return (<p>The Value is {outsideVariable}</p>)
}
In this case, the Comp
is modifying the outsideVariable
, which is defined outside of the component’s scope.
The Strict Mode
This is where React's Strict Mode comes into play. Strict Mode is a tool for highlighting potential problems in an application. It does not render any visible UI. It activates additional checks and warnings for its descendants.
It can be added by using <React.StrictMode>
tags around the application, but usually, it's wrapped around everything inside the src/index.js
file's ReactDOM.render()
method.
In Strict Mode, React performs a double-invocation of state updater functions and effect hooks for function components. This is done to ensure that the component's render output remains the same given the same state and props, irrespective of the result from previous renders.
This double-invocation helps detect such issues. It's important to note that this only happens in development mode. The double invocation isn’t performed in production.
Strict Mode also warns about deprecated methods, potential problems with legacy string ref API usage, unexpected side effects, and more. It's a powerful tool in the React ecosystem to ensure code quality and detect potential problems early in the development phase.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
In this way, React's Strict Mode helps maintain the purity of React components and ensures that side effects are minimized or eliminated, promoting predictability and maintainability.
You can read more about Strict mode from the official docs here.
https://react.dev/reference/react/StrictMode
A pure component is preferred as it can be easily cached for optimization purposes. We’ll talk about caching-related stuff later in the coming parts.
Stay tuned.
Connect -> https://twitter.com/PrakharTandon29
Posted on January 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.