The Declarative Shift
Traditional DOM manipulation is imperative: you tell the browser exactly which steps to take (e.g., “Find this element, change its color, append a child”). React introduced a declarative model: you describe what the UI should look like for a given state, and React handles the updates.
Components: The Building Blocks
In React, the UI is decomposed into small, isolated, and reusable pieces called Components. Each component is a JavaScript function that returns a description of its UI using JSX (JavaScript XML).
JSX is an extension to JavaScript that allows you to write HTML-like structures directly in your code. It is transpiled by tools like Babel into React.createElement() calls.
The Virtual DOM and Reconciliation
Direct manipulation of the real DOM is slow. To optimize updates, React maintains a Virtual DOM (VDOM)—a lightweight, in-memory representation of the real DOM.
The Diffing Algorithm
When a component’s state changes:
- React creates a new VDOM tree.
- It compares the new tree with the previous VDOM tree. This process is called Diffing.
- It calculates the minimum set of changes needed to synchronize the real DOM with the VDOM.
- It applies those changes to the real DOM in a single batch. This phase is called Commit.
One-Way Data Flow
Data in React flows in a single direction: from parent to child through Props (properties). A child component can receive data and functions via props, but it cannot directly modify the props it receives. If a child needs to communicate back to the parent, it invokes a callback function passed down through props.
This unidirectional flow makes the application state more predictable and easier to trace.
Pure Components and Immutability
React relies heavily on the concept of Purity. A component should be a “pure” function of its props and state. This means it should not have side effects during the rendering phase.
Furthermore, React uses shallow comparison of props and state to decide if a component needs to re-render. This is why immutability is critical: if you mutate an object, its reference stays the same, and React may fail to detect the change, resulting in a UI that is out of sync with your data.