React Design Philosophy
Core Philosophy of React
Declarative Programming
React’s core philosophy is declarative programming, where developers describe what the UI should look like (What) without worrying about how to achieve it (How). This contrasts with traditional imperative programming.
Example: Imperative vs. Declarative
Imperative (jQuery):
const container = document.getElementById('container');
const button = document.createElement('button');
button.textContent = 'Click me';
button.addEventListener('click', () => alert('Clicked!'));
container.appendChild(button);Declarative (React):
function Button() {
return <button onClick={() => alert('Clicked!')}>Click me</button>;
}
ReactDOM.render(<Button />, document.getElementById('container'));- React uses JSX to declare UI structure, automatically handling DOM updates.
Unidirectional Data Flow
React employs a unidirectional data flow, where data passes from parent to child components via props, and child components notify parents of updates through callbacks.
Example
function Parent() {
const [count, setCount] = useState(0);
return <Child count={count} onIncrement={() => setCount(count + 1)} />;
}
function Child({ count, onIncrement }) {
return <button onClick={onIncrement}>{count}</button>;
}- Clear data flow avoids the complexity of two-way binding.
Component-Based Architecture
React emphasizes componentization, breaking the UI into independent, reusable modules.
Example
function Header() {
return <header>My App</header>;
}
function App() {
return (
<div>
<Header />
<main>...</main>
</div>
);
}Virtual DOM
React uses a virtual DOM to optimize performance, calculating minimal updates via the Diff algorithm.
Virtual DOM Object
const vdom = {
type: 'div',
props: { children: 'Hello' }
};Design Goals
- Simplicity: Concise API, easy to learn.
- Performance: Efficient UI updates.
- Predictability: State-driven UI for consistency.
React Design Patterns
React design patterns are best practices developed by the community to address component reuse, state management, and code organization. Below are common patterns and their implementations.
Higher-Order Components (HOC)
Definition
A higher-order component is a function that takes a component as an argument and returns an enhanced component, enabling logic reuse.
Example: Adding Logging
function withLogger(WrappedComponent) {
return function EnhancedComponent(props) {
useEffect(() => {
console.log(`${WrappedComponent.name} mounted`);
return () => console.log(`${WrappedComponent.name} unmounted`);
}, []);
return <WrappedComponent {...props} />;
};
}
const MyComponent = withLogger(function MyComponent({ name }) {
return <div>Hello, {name}</div>;
});Pros and Cons
- Pros: Reuses logic, enhances component functionality.
- Cons: Can lead to deep component nesting.
Render Props
Definition
Render Props pass a render function via props, allowing components to dynamically determine rendered content.
Example: Mouse Position Tracking
function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
const handleMouseMove = (e) => setPosition({ x: e.clientX, y: e.clientY });
return <div onMouseMove={handleMouseMove}>{render(position)}</div>;
}
function App() {
return (
<MouseTracker render={({ x, y }) => <p>Position: {x}, {y}</p>} />
);
}Pros and Cons
- Pros: Flexible, reduces component nesting.
- Cons: Code may be less intuitive.
Hooks Pattern
Definition
Introduced in React 16.8, Hooks enable state and side-effect logic reuse in function components.
Example: Custom Hook
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
function App() {
const { data, loading } = useFetch('https://api.example.com');
return loading ? <div>Loading...</div> : <div>{data.message}</div>;
}Pros and Cons
- Pros: Concise, replaces HOCs and Render Props.
- Cons: Relies on call order.
Provider Pattern
Definition
The Provider pattern uses the Context API to provide global state, accessible by child components via useContext.
Example
const ThemeContext = React.createContext('light');
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
function Button() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
{theme}
</button>
);
}
function App() {
return (
<ThemeProvider>
<Button />
</ThemeProvider>
);
}Pros and Cons
- Pros: Global state management, reduces prop drilling.
- Cons: May lead to component coupling.
React Fiber Architecture
Fiber is React’s underlying implementation, supporting asynchronous rendering and Concurrent Mode. Below, we analyze its principles and source code.
Core Concepts of Fiber
Fiber Node
Fiber is React’s work unit, with each node representing a component or DOM element:
const fiber = {
tag: HostComponent, // Type (e.g., DOM node)
type: 'div', // Specific tag or component
stateNode: null, // DOM or instance
props: {}, // Current props
memoizedState: null, // Hooks or state
child: null, // Child node
sibling: null, // Sibling node
return: null, // Parent node
alternate: null, // Double buffering counterpart
lanes: NoLanes, // Priority
effectTag: NoEffect // Side effect
};Double Buffering
currenttree: Current UI.workInProgresstree: New tree being rendered.
Fiber Workflow
Render Phase
The render phase builds the workInProgress tree:
function workLoop(deadline) {
while (nextUnitOfWork && deadline.timeRemaining() > 1) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
if (!nextUnitOfWork && wipRoot) {
commitRoot(wipRoot);
}
}performUnitOfWork
function performUnitOfWork(fiber) {
if (!fiber.stateNode) {
fiber.stateNode = createDOM(fiber);
}
const children = fiber.type(fiber.props);
reconcileChildren(fiber, children);
return completeUnitOfWork(fiber);
}Commit Phase
The commit phase updates the DOM:
function commitRoot(root) {
const finishedWork = root.finishedWork;
commitMutationEffects(finishedWork);
root.current = finishedWork;
}Source Code Analysis
Creating Fiber
ReactFiber.js:
function createFiber(tag, pendingProps, key) {
return {
tag,
key,
pendingProps,
stateNode: null,
child: null,
sibling: null,
return: null,
lanes: NoLanes
};
}beginWork
ReactFiberBeginWork.js:
function beginWork(current, workInProgress, renderLanes) {
switch (workInProgress.tag) {
case FunctionComponent:
const Component = workInProgress.type;
const nextChildren = Component(workInProgress.pendingProps);
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}
}reconcileChildren
function reconcileChildren(current, workInProgress, nextChildren) {
let previousSibling = null;
let newFiber = null;
nextChildren.forEach(child => {
newFiber = createFiber(child.type, child.props, child.key);
newFiber.return = workInProgress;
if (!previousSibling) {
workInProgress.child = newFiber;
} else {
previousSibling.sibling = newFiber;
}
previousSibling = newFiber;
});
}Advanced Fiber Features
- Time Slicing: Enabled by Scheduler.
- Lane Model: Dynamic priority scheduling.
- Suspense: Supports asynchronous suspension.
Comprehensive Example and Practice
Example: Counter Application
function CounterApp() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>{count}</button>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent count={count} />
</Suspense>
</div>
);
}
const LazyComponent = React.lazy(() => Promise.resolve({ default: ({ count }) => <p>{count}</p> }));Fiber Debugging
Add logs in workLoop:
function workLoop(deadline) {
console.log('Processing:', nextUnitOfWork?.type);
// ...
}



