4.13. React Advanced Patterns – Enhancing Your Skills 🚀

Table of Contents

Hey awesome devs! 👋 It’s Vikas Sankhla here from Web Codder. Today, we’re going to level up your React skills 💪.

We’re diving into React Advanced Patterns—the secret sauce to making your apps cleaner, smarter, and reusable.

If you ever thought:

“How do I reuse logic without copying code everywhere? 🤔”

…this article is your game-changer.


🌟 What Are React Advanced Patterns?

Think of them as clever tricks to:

  • Reuse logic
  • Make components super flexible
  • Keep code DRY (Don’t Repeat Yourself)

Today we’ll cover:

1️⃣ Higher-Order Components (HOCs)
2️⃣ Render Props
3️⃣ Compound Components
4️⃣ Custom Hooks
5️⃣ Context Providers & Consumers


1️⃣ 🔁 Higher-Order Components (HOCs)

🤔 What’s an HOC?

A Higher-Order Component (HOC) is like a wrapping paper 🎁.

It wraps around your component and gives it extra powers.

It’s a function that takes a component and returns a new component.


👀 Example

Let’s say you have many components that need to show a loading spinner.

Instead of adding spinner logic everywhere, we create an HOC.

jsxCopyEditfunction withLoader(Component) {
  return function WithLoaderComponent({ isLoading, ...props }) {
    if (isLoading) return <p>Loading... ⏳</p>;
    return <Component {...props} />;
  };
}

➡️ Use it:

jsxCopyEditfunction UserProfile({ name }) {
  return <h1>{name}</h1>;
}

const UserProfileWithLoader = withLoader(UserProfile);

// Usage:
<UserProfileWithLoader isLoading={true} name="Vikas" />

✅ Why Use HOCs?

  • Reuse logic across multiple components.
  • Keep code clean and DRY.
  • Add features without touching the original component. 🔥

2️⃣ 🎨 Render Props

🤔 What’s Render Props?

It’s a pattern where you pass a function as a prop.

That function returns JSX, giving you control over what to render.


👀 Example

We want a component that tracks mouse position.

jsxCopyEditclass MouseTracker extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY,
    });
  };

  render() {
    return (
      <div onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)}
      </div>
    );
  }
}

➡️ Use it:

jsxCopyEdit<MouseTracker render={({ x, y }) => (
  <h1>The mouse is at ({x}, {y}) 🖱️</h1>
)} />

✅ Why Use Render Props?

  • Share behavior between components.
  • Super flexible: you decide what to render.

3️⃣ 🧩 Compound Components

🤔 What’s a Compound Component?

Imagine a family of components that work together.

Example: A <Tabs> component with multiple <Tab> children.

The parent controls the logic, and children just display stuff.


👀 Example

jsxCopyEditfunction Tabs({ children, activeTab, onChange }) {
  return (
    <div>
      {React.Children.map(children, (child, index) =>
        React.cloneElement(child, {
          isActive: index === activeTab,
          onClick: () => onChange(index),
        })
      )}
    </div>
  );
}

function Tab({ isActive, onClick, children }) {
  return (
    <button style={{ fontWeight: isActive ? 'bold' : 'normal' }} onClick={onClick}>
      {children}
    </button>
  );
}

➡️ Use it:

jsxCopyEditfunction App() {
  const [activeTab, setActiveTab] = React.useState(0);

  return (
    <Tabs activeTab={activeTab} onChange={setActiveTab}>
      <Tab>Tab 1</Tab>
      <Tab>Tab 2</Tab>
      <Tab>Tab 3</Tab>
    </Tabs>
  );
}

✅ Why Use Compound Components?

  • Keep logic in the parent.
  • Let children be dumb and simple.
  • Super easy to customize layout.

4️⃣ 🔄 Custom Hooks

🤔 What’s a Custom Hook?

A custom hook is just a function that starts with use and reuses React logic.

Example: You have two components that need a timer.


👀 Example

jsxCopyEditfunction useTimer(start = 0) {
  const [count, setCount] = React.useState(start);

  React.useEffect(() => {
    const interval = setInterval(() => setCount((c) => c + 1), 1000);
    return () => clearInterval(interval);
  }, []);

  return count;
}

➡️ Use it:

jsxCopyEditfunction TimerDisplay() {
  const seconds = useTimer();
  return <p>⏱️ Timer: {seconds} seconds</p>;
}

✅ Why Use Custom Hooks?

  • Reuse logic between components.
  • Keep components clean and small.
  • Use state, effects, and refs inside custom hooks.

5️⃣ 🌀 Context Providers & Consumers

🤔 What’s Context?

React’s Context API lets you share data between components without prop-drilling.

It’s like a global state.


👀 Example

1️⃣ Create Context:

jsxCopyEditconst ThemeContext = React.createContext();

2️⃣ Provide Data:

jsxCopyEditfunction App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

3️⃣ Consume Data:

jsxCopyEditfunction Toolbar() {
  return (
    <ThemeContext.Consumer>
      {(theme) => <p>Current theme: {theme} 🎨</p>}
    </ThemeContext.Consumer>
  );
}

Or use useContext:

jsxCopyEditfunction Toolbar() {
  const theme = React.useContext(ThemeContext);
  return <p>Current theme: {theme} 🎨</p>;
}

✅ Why Use Context?

  • Share data globally (like themes, user info).
  • Avoid passing props deep down the tree.

React Advanced Patterns Map
4.13. React Advanced Patterns – Enhancing Your Skills 🚀 2


✅ Quick Recap Table

PatternBest For
HOCsReusing component logic
Render PropsSharing behavior via render functions
Compound ComponentsBuilding flexible, related components
Custom HooksReusing logic inside functional components
ContextSharing global state easily

🏁 Conclusion: You’re Now an Advanced React Ninja! 🥷

Awesome work, coder fam! 🚀 You’ve learned:

  • What advanced React patterns are ✅
  • How to reuse logic and keep code clean
  • Cool patterns like HOCs, Render Props, Custom Hooks, and more ✅

Your React skills just leveled up! 🔥


👉 Subscribe & follow for more awesome content:

Let’s keep learning and building amazing stuff together! 💪

Share the Post:
Picture of Web Codder

Web Codder

Vikas Sankhla is a seasoned Full Stack Developer with over 7 years of experience in web development. He is the founder of Web Codder, a platform dedicated to providing comprehensive web development tutorials and resources. Vikas specializes in the MERN stack (MongoDB, Express.js, React.js, Node.js) and has been instrumental in mentoring aspiring developers through his online courses and content. His commitment to simplifying complex web technologies has made him a respected figure in the developer community.

Related Posts