Skip to main content

Featured

🎉 Day 46 — React Mastery Completed (Final Summary & Congratulations!)

🎉 Day 46 — React Mastery Completed (Final Summary & Congratulations!) Congratulations, developer! 👏 You’ve successfully completed the 45-Day React.js Roadmap — from understanding the fundamentals to mastering advanced concepts like Redux, Routing, Testing, and Deployment. 📘 What You’ve Learned ✅ React basics — Components, JSX, Props, and State ✅ Hooks — useState, useEffect, useRef, useMemo, and Custom Hooks ✅ Context API and Redux Toolkit for global state management ✅ Routing with React Router & Protected Routes ✅ Data fetching using Fetch API, Axios, React Query ✅ Advanced Patterns — Compound Components, Render Props, HOCs ✅ Styling — CSS Modules, Styled Components, Theming ✅ Animations, Accessibility, Testing, and Performance Optimization ✅ Deployment on Vercel, Netlify, or GitHub Pages 🧩 Final Project Ideas Now that you’re done, build real-world apps to polish your skills: 📝 Task ...

🧩 Day 37 — React Patterns: Compound Components, Render Props & HOCs

🧩 Day 37 — React Patterns: Compound Components, Render Props & HOCs

As React apps grow, managing component logic efficiently becomes crucial. Today, we’ll explore three advanced patterns — Compound Components, Render Props, and Higher-Order Components (HOCs).

🔹 Compound Components

They let multiple components work together while sharing implicit state.

function Toggle({ children }) {
  const [on, setOn] = React.useState(false);
  return React.Children.map(children, child =>
    React.cloneElement(child, { on, setOn })
  );
}

Toggle.On = ({ on, children }) => on ? children : null;
Toggle.Off = ({ on, children }) => (on ? null : children);
Toggle.Button = ({ on, setOn }) => (
  <button onClick={() => setOn(!on)}>{on ? "ON" : "OFF"}</button>
);
  

This allows clean and flexible API design for shared logic.

💡 Render Props

Pass a function as a child to share reusable logic.

function MouseTracker({ render }) {
  const [pos, setPos] = React.useState({ x: 0, y: 0 });
  return (
    <div onMouseMove={(e) => setPos({ x: e.clientX, y: e.clientY })}>
      {render(pos)}
    </div>
  );
}
  

🏗 Higher-Order Components (HOCs)

A HOC is a function that takes a component and returns a new one, enhancing its behavior.

function withLogger(WrappedComponent) {
  return function Enhanced(props) {
    console.log("Props:", props);
    return <WrappedComponent {...props} />;
  };
}
  

Understanding these patterns helps build reusable and scalable React components that maintain clarity and flexibility.

Comments