Sub topic 1
Elements, Components, and JSX: What a Component Returns
Prerequisites
Assume you know JavaScript functions, objects, and arrays; basic React components, props, and JSX; the useState hook; and the browser DOM.
Elements, components, and JSX
A component is a JavaScript function that returns a description of user interface. An element is the object React creates from that description. JSX is JavaScript syntax that makes elements easier to write.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
console.log('rendering', count);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}<button> is JSX. React turns it into an element object. Counter is the component. The returned element does not directly change the DOM. It tells React what the UI should look like.
A component can return an element, a group of elements, or null. Components can also return other components:
function App() {
return <Counter />;
}The Counter element records the component type and its props. React later uses that information to decide what work is needed.
Rendering as a pure calculation
Rendering means calling components to calculate the next UI description from their inputs.
| Input | Meaning |
|---|---|
| Props and state | Values that determine the returned UI |
A pure render has no observable side effects. Given the same props and state, it returns the same result. Do not start network requests, modify the DOM, or change external variables during rendering. Use event handlers or effects for those actions.
What triggers a re-render
React schedules a re-render when a component's state setter receives an update. A parent re-render also normally causes its children to render again. A changed prop or context value can do the same.
A re-render does not mean React rebuilds every DOM node. It recalculates elements first, then compares the new result with the previous result.
The render phase and the commit phase
React separates the work into two phases:
- Render phase: React calls components and builds a new element tree.
- Commit phase: React applies the necessary changes to the DOM.
React may perform or discard render-phase work before committing it. Therefore, render functions must stay pure. The commit phase is the point at which changes become visible in the DOM.
Exercise
If a component renders again, must React replace its button in the DOM?
Show answer
No. React calculates a new element tree and commits only the DOM changes required by the comparison.