React patterns
React patterns are proven ways to design reusable components so they stay flexible as requirements grow. This video covers composition (slots), compound components, render props, HOCs and the custom hook pattern, and when to use each.
41.1 Why is it used?
- A generic component that gets a new prop for every requirement ends up with prop explosion (8 props for one simple Card).
- Each new prop adds another if inside the component, so it becomes rigid and risky to change.
- Patterns split responsibilities: the component owns layout or logic, the caller owns content or UI.
- The same ideas power libraries you use every day (Radix and shadcn Tabs/Accordion, React.memo, renderItem props).
React (JSX)
export function OrderCard({ track }) { return ( <Card title="Order #42" showBadge badgeText="New" showButton buttonText="Track" onButtonClick={track} showFooter footerText="Arriving tomorrow" /> );}- Step 1
1.New requirement (image, second button...)
- Step 2
2.Card gets one more prop
- Step 3
3.Card gets one more if inside
- Step 4
4.Component becomes rigid and risky to change
- Step 5
5.Fix: Card gives layout, caller passes content
Composition moves content decisions to the caller
41.2 Composition and slots
- Card takes only header, footer and children; each can be full JSX, not just text.
- Card only places them in the right spot: layout belongs to Card, content belongs to the caller.
- These named places (header, footer, children) are called slots.
- Need a button or an image? Card never changes.
React (JSX)
function Card({ header, footer, children }) { return ( <div className="card"> <header>{header}</header> <main>{children}</main> <footer>{footer}</footer> </div> );} export default Card;React (JSX)
import Card from "./Card"; export default function OrderCard({ track }) { return ( <Card header={<h3>Order #42 · New</h3>} footer={<p>Arriving tomorrow</p>} > <p>Paid via UPI</p> <button onClick={track}>Track</button> </Card> );}Output
# Order #42 · NewPaid via UPI[button] TrackArriving tomorrow41.3 Compound components: Tabs
- Several components that work together as one family, like HTML <select> and <option>.
- The parent (Tabs) owns the state (active) and shares it through context.
- Each child (Tab, Panel) reads only what it needs from context.
- The caller never passes active around; the markup reads like HTML.
React (JSX)
import { createContext, useState } from "react"; export const TabsContext = createContext(null); export function Tabs({ children }) { const [active, setActive] = useState(0); return ( <TabsContext value={{ active, setActive }}> {children} </TabsContext> );}React (JSX)
import { useContext } from "react";import { TabsContext } from "./Tabs";export function Tab({ index, children }) { const { setActive } = useContext(TabsContext); return ( <button onClick={() => setActive(index)}> {children} </button> );} export function Panel({ index, children }) { const { active } = useContext(TabsContext); return active === index ? children : null;}React (JSX)
import { Tabs } from "./Tabs";import { Tab, Panel } from "./TabParts"; export default function ProductTabs() { return ( <Tabs> <Tab index={0}>Details</Tab> <Tab index={1}>Reviews</Tab> <Panel index={0}>6 GB RAM, 5G</Panel> <Panel index={1}>Rated 4.5 stars</Panel> </Tabs> );}Output
-- initial --[button] Details[button] Reviews6 GB RAM, 5G -- after clicking Reviews --[button] Details[button] ReviewsRated 4.5 stars- Step 1
1.<Tabs> owns state: active = 0
- Step 2
2.TabsContext shares { active, setActive }
- Step 3
3.<Tab index={1}> click calls setActive(1)
- Step 4
4.<Panel index={1}> sees active === 1 and renders
- Step 5
5.Other Panels return null
Radix and shadcn Tabs/Accordion use this pattern
41.4 Checkpoint: two Tabs on one page
- Compare renders ProductTabs twice. Click Reviews in the first one: what does the second show?
- Answer: Details. Every <Tabs> has its own provider and its own state, so a click only affects its own children.
React (JSX)
import ProductTabs from "./ProductTabs"; export default function Compare() { return ( <> <ProductTabs /> <ProductTabs /> </> );}Output
-- initial --[button] Details[button] Reviews6 GB RAM, 5G[button] Details[button] Reviews6 GB RAM, 5G -- after clicking Reviews in the first Tabs --[button] Details[button] ReviewsRated 4.5 stars[button] Details[button] Reviews6 GB RAM, 5G41.5 Render props
- The component handles the logic, the caller decides the UI through a function prop.
- Toggle keeps the on state and renders nothing itself: it calls render(on, flip).
- The caller returns a button, so a click switches Show password to Hide password.
React (JSX)
import { useState } from "react"; function Toggle({ render }) { const [on, setOn] = useState(false); return render(on, () => setOn((v) => !v));} export default function App() { return <Toggle render={(on, flip) => ( <button onClick={flip}> {on ? "Hide" : "Show"} password </button> )} />;}Output
-- initial --[button] Show password -- after click --[button] Hide password41.6 HOC (higher order component)
- A function that takes a component and returns a new component with extra behaviour.
- withAuth returns Protected: no user shows "Please log in", otherwise it renders the original component with all props.
- SafeOrders = withAuth(Orders) is created once at the top level.
React (JSX)
function withAuth(Component) { return function Protected(props) { if (!props.user) { return <p>Please log in</p>; } return <Component {...props} />; };} function Orders({ user }) { return <p>{user}'s orders</p>;} export const SafeOrders = withAuth(Orders);Output
-- user missing --Please log in -- with user="Priya" --Please log inPriya's orders41.7 Custom hook pattern
- useToggle holds the same logic Toggle had: state plus a flip function.
- The component calls the hook and returns the button directly: no wrapper, no function prop.
- Same result, so today a custom hook is the first choice for sharing logic.
React (JSX)
import { useState } from "react"; function useToggle(initial = false) { const [on, setOn] = useState(initial); return [on, () => setOn((v) => !v)];} export default function PasswordToggle() { const [on, flip] = useToggle(); return ( <button onClick={flip}> {on ? "Hide" : "Show"} password </button> );}Output
-- initial --[button] Show password -- after click --[button] Hide password41.8 Comparison: the patterns
| Pattern | What it shares | Who decides the UI | Example |
|---|---|---|---|
| Composition / slots | Layout | Caller (children, header, footer) | Card |
| Compound components | State via context | Caller arranges the children | Tabs, Tab, Panel |
| Render props | Logic + values passed to a function | Caller's render function | Toggle render={...}, renderItem |
| HOC | Behaviour wrapped around a component | Wrapped component | withAuth(Orders), memo |
| Custom hook | Stateful logic | The component that calls the hook | useToggle |
41.9 When to use which
- Flexible layout: composition with children and slots.
- A family of components sharing one state: compound components.
- Reusing logic: think custom hook first.
- Handing over rendering control or following a library's API: render props or an HOC.
41.10 Common mistakes
- Calling an HOC inside a component: every render creates a brand new component type, React unmounts the old one and its state resets.
- Fix: call the HOC once at the top level of the file.
- Adding one more boolean prop for every new requirement instead of using slots.
- Myth: HOCs and render props are dead after hooks. Hooks are better for logic, but memo is HOC style and many libraries still use renderItem-style render props.
React (JSX)
function Page({ user }) { const SafeOrders = withAuth(Orders); return <SafeOrders user={user} />;}React (JSX)
const SafeOrders = withAuth(Orders); function Page({ user }) { return <SafeOrders user={user} />;}41.11 Interview tips
- Composition makes a component flexible: the component owns layout, the caller owns content.
- Compound components share state through context so they work together like a family (Tabs, Tab, Panel).
- Render props: a function prop decides the UI. HOC: a function that wraps a component and returns a new one.
- Today custom hooks are preferred for reusing logic because they avoid wrapper nesting ("wrapper hell").
- Never create an HOC inside render: it resets state on every render.