"course_name": "https://www.youtube.com/watch?v=qg-_EVPqizM&t=3545s",
From the https://www.youtube.com/watch?v=qg-_EVPqizM&t=3545s curriculum
Advanced React Patterns for Scalability
TL;DR
This lesson explores advanced React patterns like Compound Components, Control Props, and State Reducers to build more flexible and reusable components. You'll learn how these patterns improve component design by separating concerns and providing explicit control over behavior. Mastering these patterns helps you write highly scalable and maintainable React applications.
1. The Mental Model
Think of these patterns as special toolkits for building LEGOs. Instead of making one big, fixed LEGO castle, you're creating individual LEGO bricks and instructions that let others build their own castles, with options to customize how each piece works or connects. This makes your components super adaptable.
2. The Core Material
When building complex UIs, standard components can become rigid or difficult to reuse. Advanced patterns give you more control and flexibility.
Compound Components: Grouping Related Functionality

Photo by Nic Wood on Pexels
Compound Components allow you to build components that work together implicitly, sharing state and logic without prop drilling. Think of a <Select> component with <Select.Option> children. They look like separate components, but they're tightly coupled.
// Simplified example of a Compound Component pattern
import React, { createContext, useContext, useState } from 'react';
// 1. Create a Context to share state
const ToggleContext = createContext();
// 2. The Parent Component manages state and provides it via Context
function Toggle({ children }) {
const [on, setOn] = useState(false);
const toggle = () => setOn(prevOn => !prevOn);
// Provide state and functions to children
return (
<ToggleContext.Provider value={{ on, toggle }}>
{children}
</ToggleContext.Provider>
);
}
// 3. Child Components consume the state from Context
function ToggleOn({ children }) {
const { on } = useContext(ToggleContext);
return on ? children : null;
}
function ToggleOff({ children }) {
const { on } = useContext(ToggleContext);
return on ? null : children;
}
function ToggleButton() {
const { on, toggle } = useContext(ToggleContext);
return (
<button onClick={toggle}>
{on ? 'On' : 'Off'}
</button>
);
}
// How you'd use it:
function App() {
return (
<Toggle>
<ToggleOn>The light is on!</ToggleOn>
<ToggleOff>The light is off!</ToggleOff>
<ToggleButton />
</Toggle>
);
}
// export default App; // Uncomment to run
This pattern makes the Toggle component highly composable. You can arrange its ToggleOn, ToggleOff, and ToggleButton parts however you like, and they'll always work together.
Control Props: Externalizing State Management

Photo by André Eusébio on Pexels
The Control Props pattern allows a parent component to fully control the state of its child component. This means the child component's internal state can be overridden by props, making it either "controlled" (managed by the parent) or "uncontrolled" (managed internally).
It's common in form inputs where you might want to control value and onChange from a parent.
// Example of a Control Props pattern
import React, { useState } from 'react';
function ControlledInput({ value, onChange, defaultValue, ...props }) {
// If 'value' prop is provided, the component is controlled.
// Otherwise, it manages its own state using 'defaultValue'.
const isControlled = value !== undefined;
const [internalValue, setInternalValue] = useState(defaultValue || '');
const handleChange = (event) => {
if (!isControlled) {
setInternalValue(event.target.value);
}
// Always call onChange if it exists, whether controlled or not
if (onChange) {
onChange(event);
}
};
return (
<input
value={isControlled ? value : internalValue}
onChange={handleChange}
{...props}
/>
);
}
// How you'd use it:
function App() {
const [parentValue, setParentValue] = useState("Hello");
const handleParentChange = (e) => {
setParentValue(e.target.value);
};
return (
<div>
<p>Controlled Example:</p>
<ControlledInput
value={parentValue}
onChange={handleParentChange}
/>
<p>Parent Value: {parentValue}</p>
<p>Uncontrolled Example:</p>
<ControlledInput defaultValue="World" />
</div>
);
}
// export default App; // Uncomment to run
The key here is that if a value prop is passed, the ControlledInput uses it; otherwise, it manages its own internalValue. This gives users of the component the flexibility to choose.
State Reducers: Customizing State Transitions

Photo by Airam Dato-on on Pexels
The State Reducer pattern allows consumers of your component to customize how its internal state changes. Instead of directly calling setState, the component calls a reducer function (provided via props) with the current state and an action. This gives the consumer the power to intercept and modify the state update logic.
It's particularly powerful when you need complex state management within a reusable component, but want to allow consumers to add custom logic without forking the component.
// Example of a State Reducer pattern
import React, { useReducer } from 'react';
// Default reducer for the toggle component
const toggleReducer = (state, action) => {
switch (action.type) {
case 'TOGGLE':
return { on: !state.on };
case 'RESET':
return { on: action.initialOn };
default:
return state;
}
};
function useToggle({ initialOn = false, reducer = toggleReducer } = {}) {
const [{ on }, dispatch] = useReducer(reducer, { on: initialOn });
const toggle = () => dispatch({ type: 'TOGGLE' });
const reset = () => dispatch({ type: 'RESET', initialOn });
return { on, toggle, reset };
}
// How you'd use it:
function App() {
// Custom reducer: always turn on, never off.
const customReducer = (state, action) => {
if (action.type === 'TOGGLE' && state.on === false) {
return { on: true }; // Only allow turning ON
}
return toggleReducer(state, action); // Use default for other actions
};
const { on: defaultOn, toggle: defaultToggle, reset: defaultReset } = useToggle({ initialOn: false });
const { on: customOn, toggle: customToggle, reset: customReset } = useToggle({ reducer: customReducer, initialOn: false });
return (
<div>
<h3>Default Toggle</h3>
<p>State: {defaultOn ? 'On' : 'Off'}</p>
<button onClick={defaultToggle}>Toggle</button>
<button onClick={defaultReset}>Reset</button>
<h3>Custom Toggle (always On)</h3>
<p>State: {customOn ? 'On' : 'Off'}</p>
<button onClick={customToggle}>Toggle (tries to turn off, but reducer prevents)</button>
<button onClick={customReset}>Reset</button>
</div>
);
}
// export default App; // Uncomment to run
The useToggle hook accepts an optional reducer prop. If provided, that reducer is used to determine the next state. If not, the toggleReducer is used. This allows powerful customization of behavior.
graph TD
A["Component Consumer Needs"] --> B{Does a default component work?};
B -- No --> C{Do you need to group related UIs?};
C -- Yes --> D["Use Compound Components"];
D --> E["Example: <Select><Select.Option>"];
C -- No --> F{Do you need parent control over internal state?};
F -- Yes --> G["Use Control Props"];
G --> H["Example: <Input value={...} onChange={...}/>"];
F -- No --> I{Do you need to customize how state changes occur?};
I -- Yes --> J["Use State Reducer"];
J --> K["Example: useToggle({ reducer: myCustomReducer })"];
B -- Yes --> L["Use a Standard Component"];
L --> M["Example: <Button onClick={...}/>"];
3. Worked Example
Let's imagine you're building a Modal component. You want it to be flexible: sometimes you need a simple "open/close" toggle, and sometimes you need fine-grained control from the parent, like forcing it open based on some external data, or intercepting its close behavior.
Using the Control Props pattern, you can achieve this:
```jsx
import React, { useState } from 'react';
import ReactDOM from 'react-dom'; // Needed for portal
// The Modal component using Control Props
function Modal({
isOpen, // Controlled prop: if provided, the parent dictates open/close
onClose, // Controlled prop: callback when close is requested
initialIsOpen = false, // Uncontrolled prop: default open state if not controlled
children,
}) {
// Determine if the component is controlled by parent props
const isControlled = isOpen !== undefined;
// Internal state for uncontrolled mode
const [internalIsOpen, setInternalIsOpen] = useState(initialIsOpen);
// The actual open state, either from props or internal
const displayIsOpen = isControlled ? isOpen : internalIsOpen;
const handleClose = () => {
// If not controlled, update internal state
if (!isControlled) {
setInternalIsOpen(false);
}
// Always call the onClose prop if it exists
if (onClose) {
onClose();
}
};
if (!displayIsOpen) return null;
// Render the modal content using a Portal for better accessibility/DOM placement
return ReactDOM.createPortal(
{children}
document.body // Portal
Frequently asked about "course_name": "https://www.youtube.com/watch?v=qg-_EVPqizM&t=3545s",
Get the full https://www.youtube.com/watch?v=qg-_EVPqizM&t=3545s curriculum
Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.
Create Free Account