How to Update JSX in React
To update JSX in React, you do not manipulate the DOM directly;
instead, you trigger a re-render of the component by changing its state
or props. This article explains how React handles UI updates, how to use
the useState hook to dynamically change JSX, and how the
virtual DOM efficiently applies these changes to the screen.
Understanding JSX Immutability
JSX elements are immutable. Once you create a JSX element, you cannot change its children or attributes directly. To change what appears on the screen, you must create new JSX elements by triggering a component re-render. React compares the new JSX with the old JSX and updates only the necessary parts of the actual browser DOM.
Updating JSX with React State
The primary way to update JSX is by using State. When a component’s state changes, React automatically re-renders the component and updates the JSX to reflect the new state.
In functional components, you manage state using the
useState hook.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}In this example: 1. The variable count is embedded in
the JSX: {count}. 2. Clicking the button calls
setCount(count + 1). 3. React detects the state change,
re-renders the Counter component, generates new JSX with
the updated count value, and updates the DOM.
Updating JSX with Props
JSX also updates when a component receives new Props from its parent component. When a parent component’s state changes, it can pass the updated state down to a child component as a prop.
// Parent Component
function App() {
const [theme, setTheme] = useState('light');
return (
<div>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
<Display theme={theme} />
</div>
);
}
// Child Component
function Display({ theme }) {
return <p>The active theme is {theme}.</p>;
}Whenever the App component’s state changes, the
Display component receives the new theme prop,
causing its JSX to re-render and display the updated theme.
How React Updates the DOM (The Virtual DOM)
React uses a “Virtual DOM” to make JSX updates highly performant. The process follows three steps:
- Render: When state or props change, React executes the component function and generates a new Virtual DOM tree representing the updated JSX.
- Diffing: React compares the new Virtual DOM tree with a snapshot of the previous Virtual DOM tree to identify exactly what changed.
- Reconciliation: React updates only the specific elements in the real browser DOM that changed, rather than rebuilding the entire page.