JavaScript

10 React Patterns That Simplify Complex Components

Learn 10 React patterns that simplify complex components. Explore Custom Hooks, Composition, Context API, Compound Components, and more with practical examples.

R
Ruhan Ahmed
Dec 1, 2026
17 min read
Table of Contents
10 React Patterns That Simplify Complex Components

When you first start working with React, building components feels pretty easy. You create a component, add some state, pass a few props, and you're done. But things change as your application grows. A component that once had 20 lines of code might now have 200. It handles API calls, manages state, checks user input, and renders the UI. Making even a small change starts to feel like a headache. Sound familiar?

This is where React patterns can help. They give you better ways to organize your code, reuse logic, and keep components simple. In this article, we'll look at 10 React patterns that simplify complex components. I'll explain how each one works, show simple code examples, and discuss when you should actually use it. You don't need all these patterns in every project. Just learn what problem each one solves.

Read article on "12 React Form Mistakes"

1. Container and Presentational Components

Let's start with a simple problem. Imagine you're building a product page. One component fetches products from an API, manages loading states, handles errors, and displays the products.

That's a lot of work for one component. What if you split those tasks into two components?

That's exactly what the Container and Presentational pattern does. Container Component: Handles data, API calls, and application logic. Presentational Component: Takes data through props and displays it on the screen. Let's see how it works.

Example

First, create a container component:

import { useEffect, useState } from "react";

function ProductContainer() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch("/api/products")
      .then((res) => res.json())
      .then(setProducts);
  }, []);

  return <ProductList products={products} />;
}

Now create a separate component to display the products:

function ProductList({ products }) {
  return (
    <div>
      {products.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>${product.price}</p>
        </div>
      ))}
    </div>
  );
}

See the difference?

ProductContainer handles the data. ProductList only displays it.

Now, if you want to change the design, you don't need to touch the API logic. You can also reuse ProductList somewhere else with different product data.

When should you use it?

This pattern is useful when:

  • A component is doing too many things.

  • You want to reuse the same UI in different places.

  • You want to test data handling and UI separately.

  • Your application has a lot of API-driven components.

My advice: Don't split every component into a container and a presentational component. If the component is already simple, leave it alone.

Read article on "What to Know Before Learning Next.js in 2026"

2. Custom Hooks for Reusing Logic

Custom Hooks are probably one of the most useful React features. Here's a common situation. You have three different components. All of them need to track the browser window size. You could write the same useState, useEffect, and resize event code in all three components.

But why repeat the same code?

Instead, you can put that logic inside a Custom Hook and reuse it wherever you need. A Custom Hook is just a JavaScript function that starts with use and uses React Hooks inside it.

Example

Let's create a Hook called useWindowSize.

import { useEffect, useState } from "react";

function useWindowSize() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    function handleResize() {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return size;
}

Now you can use it inside any component:

function Dashboard() {
  const { width, height } = useWindowSize();

  return (
    <div>
      <p>Width: {width}px</p>
      <p>Height: {height}px</p>
    </div>
  );
}

That's it. You don't need to write the resize logic again. Just call useWindowSize(). This is especially helpful when working with forms, API requests, authentication, browser events, and other repeated tasks.

When should you use Custom Hooks?

Use them when:

  • You find yourself writing the same logic in multiple components.

  • A component has too much state-related code.

  • You want to separate logic from the UI.

  • You need to share behavior between different components.

My advice: Give your Hooks clear names and keep them focused on one job. Don't create a Custom Hook just to move a few lines of code into another file. One more thing: Hooks must be called at the top level of React components or other Hooks. Don't call them inside loops, conditions, or event handlers.

Read article on "How to Optimize React Performance"

3. Composition Over Inheritance

Here's a simple question. If you want to build a large UI, would you rather write one huge component or combine several smaller components?

Most React developers would choose the second option. That's the idea behind Composition. Instead of building complex components through inheritance, you create small components and put them together. Think about a product card. It might contain:

  • A product image.

  • A product name.

  • A price.

  • A rating.

  • An Add to Cart button.

You don't need to handle everything inside one component. Each part can have its own component.

Example

function ProductImage({ src }) {
  return <img src={src} alt="Product" />;
}

function ProductInfo({ name, price }) {
  return (
    <div>
      <h3>{name}</h3>
      <p>${price}</p>
    </div>
  );
}

function AddToCartButton() {
  return <button>Add to Cart</button>;
}

function ProductCard() {
  return (
    <article>
      <ProductImage src="/product.jpg" />
      <ProductInfo
        name="Wireless Headphones"
        price={99}
      />
      <AddToCartButton />
    </article>
  );
}

Here, ProductCard brings everything together. Each smaller component has its own job. You can change the product image, information, or button without changing the entire component. You can also use the children prop to make components more flexible.

function Card({ children }) {
  return <div className="card">{children}</div>;
}

Now you can put almost anything inside it:

function App() {
  return (
    <Card>
      <h2>Welcome Back!</h2>
      <p>Continue where you left off.</p>
      <button>Open Dashboard</button>
    </Card>
  );
}

The Card component doesn't care what you put inside it. It simply provides the outer structure.

When should you use Composition?

Composition works well when:

  • You're building reusable UI components.

  • You have large pages with many smaller sections.

  • Different pages need different versions of the same component.

  • You want to keep components easy to change.

My advice: Don't turn every small HTML element into a separate React component. Split things when they have a real purpose.

Read article on "How Does unknown Protect Your TypeScript Code?"

4. Compound Components

Have you ever built a Tabs component?

You probably needed a parent component, some tab buttons, and separate content for each tab. Now imagine building the same thing for an Accordion or Dropdown. All these components have something in common: their child components need to share information. This is where Compound Components come in. With this pattern, several related components work together and share state through React Context. For example, a Tabs component can have:

  • Tabs — manages the active tab.

  • Tab — displays a tab button.

  • TabPanel — displays the content of the selected tab.

Example

First, create a shared context:

import { createContext, useContext, useState } from "react";

const TabsContext = createContext(null);

function Tabs({ children }) {
  const [activeTab, setActiveTab] = useState("profile");

  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      {children}
    </TabsContext.Provider>
  );
}

Now create the tab button:

function Tab({ value, children }) {
  const context = useContext(TabsContext);

  if (!context) {
    throw new Error("Tab must be used inside Tabs");
  }

  return (
    <button
      onClick={() => context.setActiveTab(value)}
      aria-selected={context.activeTab === value}
    >
      {children}
    </button>
  );
}

And the tab content:

function TabPanel({ value, children }) {
  const context = useContext(TabsContext);

  if (!context) {
    throw new Error("TabPanel must be used inside Tabs");
  }

  if (context.activeTab !== value) {
    return null;
  }

  return <div>{children}</div>;
}

Now you can use all three components together:

function App() {
  return (
    <Tabs>
      <Tab value="profile">Profile</Tab>
      <Tab value="settings">Settings</Tab>

      <TabPanel value="profile">
        <h2>Your Profile</h2>
      </TabPanel>

      <TabPanel value="settings">
        <h2>Your Settings</h2>
      </TabPanel>
    </Tabs>
  );
}

Notice something?

You don't need to pass activeTab and setActiveTab to every child. They can access the shared state themselves. The example is intentionally small. A real Tabs component should also support keyboard navigation, focus handling, and proper accessibility attributes.

When should you use Compound Components?

They're useful when:

  • Several components need to share state.

  • You're building Tabs, Accordions, or Dropdowns.

  • You want developers to control how child components are arranged.

  • Passing props through multiple component levels becomes annoying.

My advice: Keep the structure easy to understand. If someone uses your component, they should know which child components belong inside the parent.

Read article on "TypeScript Types vs Interfaces"

5. Controlled and Uncontrolled Components

If you've worked with React forms, you've probably seen both of these approaches. They solve the same problem: managing input values. But they work differently. The main difference is simple: Who controls the input value?

Controlled Components

In a controlled component, React state controls the input value. Every time someone types something, React updates the state.

import { useState } from "react";

function ControlledInput() {
  const [name, setName] = useState("");

  return (
    <div>
      <input
        value={name}
        onChange={(event) => setName(event.target.value)}
      />

      <p>Your name: {name}</p>
    </div>
  );
}

Here, the name state always holds the current input value. This makes it easy to validate inputs, show error messages, and update other parts of the UI.

Uncontrolled Components

In an uncontrolled component, the browser manages the input value. React doesn't need to update state every time someone types. You can read the value later using useRef.

import { useRef } from "react";

function UncontrolledInput() {
  const inputRef = useRef(null);

  function handleSubmit() {
    alert(inputRef.current.value);
  }

  return (
    <div>
      <input ref={inputRef} defaultValue="John" />

      <button onClick={handleSubmit}>
        Submit
      </button>
    </div>
  );
}

Here, React reads the value only when the user clicks the button.

Controlled vs. Uncontrolled Components

Feature

Controlled

Uncontrolled

Value managed by

React state

Browser DOM

Main property

value

defaultValue

Reading changes

onChange

Usually ref

Validation

Easier to manage

Needs extra handling

Best for

Complex forms

Simple inputs

When should you use each one?

Use controlled components when you need to manage input values, validate forms, or update the UI while someone types. Use uncontrolled components when you only need to read a value occasionally.

My advice: For most complex forms, controlled components are a good choice. For simple inputs, uncontrolled components can save you some extra code.

Just don't switch between the two approaches while the component is running.

Read article on "Is Node.js 27 Going to Break Your Existing Applications?"

6. Context API for Sharing Data

Let's say you have a dashboard. Your application has a Navbar, Sidebar, Profile page, and Settings page. All of them need access to the current user's information. How would you pass that data around? You could pass it through props from the parent to the child, then to another child, and so on. But imagine doing that across ten or fifteen component levels. That's called prop drilling. React Context helps solve this problem. It lets you share data with components without passing props through every level.

Example

First, create a Theme Context:

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function ThemeProvider({ children }) {
  return (
    <ThemeContext.Provider value="dark">
      {children}
    </ThemeContext.Provider>
  );
}

Now, any child component can access the theme:

function ThemeButton() {
  const theme = useContext(ThemeContext);

  return (
    <button className={`button-${theme}`}>
      Current Theme: {theme}
    </button>
  );
}

Use the provider in your application:

function App() {
  return (
    <ThemeProvider>
      <ThemeButton />
    </ThemeProvider>
  );
}

That's all.

ThemeButton can access the theme without receiving it through props.

When should you use Context API?

It's useful for sharing:

  • User information.

  • Theme settings.

  • Language preferences.

  • Authentication state.

  • Application configuration.

But don't use Context for everything.

If you put every piece of application state into one large context, it can become difficult to manage. Changes to context values can also cause consumers to re-render.

My advice: Keep your contexts separate. For example, create one for themes, another for authentication, and another for user preferences.

Also, don't put frequently changing values into a context used by your entire application unless there's a good reason.

Read article on "5 Slow Node.js Patterns"

7. Provider Pattern and Dependency Injection

The Provider pattern is closely related to Context API. But there's a small difference. Context gives you a way to share values. The Provider pattern is an approach to supplying shared services and settings to different components. For example, imagine several components need to make API requests. You could create a new API client inside every component. But that's unnecessary. Instead, create the API client once and provide it to the components that need it. This is called Dependency Injection. In simple words, a component gets the tools it needs from somewhere else instead of creating those tools itself.

Example

First, create an API context and provider:

import { createContext, useContext } from "react";

const ApiContext = createContext(null);

function ApiProvider({ client, children }) {
  return (
    <ApiContext.Provider value={client}>
      {children}
    </ApiContext.Provider>
  );
}

function useApi() {
  const client = useContext(ApiContext);

  if (!client) {
    throw new Error("useApi must be used inside ApiProvider");
  }

  return client;
}

Now a component can use the API client:

function UserProfile() {
  const api = useApi();

  return <h2>User Profile</h2>;
}

And provide the client from the parent:

function App({ apiClient }) {
  return (
    <ApiProvider client={apiClient}>
      <UserProfile />
    </ApiProvider>
  );
}

The UserProfile component doesn't need to know how the API client was created. It simply gets the client from the provider. This also makes testing easier. You can provide a fake API client during tests instead of calling a real API.

When should you use the Provider pattern?

Use it when:

  • Many components need the same service.

  • You want to share an API client or logger.

  • You need to replace services during testing.

  • You want to keep application configuration in one place.

My advice: Don't create a huge provider that handles everything. Keep providers focused on their own jobs.

Read article on "Cloudflare Python Workers"

8. Render Props

Render Props is another way to share logic between React components. The idea is pretty simple. A component receives a function as a prop. It passes some data to that function, and the function decides what to display.

Why would you need this?

Imagine you have a component that tracks the mouse position. One page might want to display the coordinates as text. Another might want to use them to move an element around.

The tracking logic is the same, but the UI is different. Render Props lets you reuse the logic without forcing everyone to use the same UI.

Example

Let's create a MouseTracker component:

import { useState } from "react";

function MouseTracker({ render }) {
  const [position, setPosition] = useState({
    x: 0,
    y: 0,
  });

  return (
    <div
      onMouseMove={(event) => {
        setPosition({
          x: event.clientX,
          y: event.clientY,
        });
      }}
    >
      {render(position)}
    </div>
  );
}

Now use it:

function App() {
  return (
    <MouseTracker
      render={({ x, y }) => (
        <p>
          Mouse Position: {x}, {y}
        </p>
      )}
    />
  );
}

The MouseTracker handles the mouse position. The parent decides how to display it.

When should you use Render Props?

They're useful when:

  • Different components need the same behavior but different UI.

  • You want to give developers control over rendering.

  • You're working with an existing library that uses this pattern.

My advice: For new React code, Custom Hooks are often simpler. If you only need to share logic, a Hook will usually do the job with less nesting. Render Props still make sense when the rendering function is an important part of the component's API.

9. Higher-Order Components (HOCs)

Higher-Order Components, usually called HOCs, are another way to reuse logic in React. A HOC is a function that takes a component and returns a new component with some extra features. Think of it like wrapping an existing component to give it more functionality. For example, imagine you have several pages that should only be available to logged-in users. Instead of writing the same authentication check in every page, you can create one HOC.

Example

Let's create a simple authentication HOC:

function withAuth(Component) {
  return function ProtectedComponent({
    isLoggedIn,
    ...props
  }) {
    if (!isLoggedIn) {
      return <p>Please log in to continue.</p>;
    }

    return <Component {...props} />;
  };
}

Now create a normal component:

function Dashboard() {
  return <h2>Welcome to your Dashboard!</h2>;
}

Wrap it with the HOC:

const ProtectedDashboard = withAuth(Dashboard);

And use it:

function App() {
  return <ProtectedDashboard isLoggedIn={true} />;
}

That's how a Higher-Order Component works. The original Dashboard component doesn't need to handle the authentication check. The HOC takes care of it. Keep in mind, this is only a UI example. Real authentication and permission checks must also happen on the server.

When should you use HOCs?

HOCs can be useful when:

  • You're working with older React projects.

  • A library already uses HOCs.

  • You need to add shared behavior to existing components.

  • You're working with class-based components.

My advice: If you're starting a new React project, Custom Hooks are often a better option for sharing logic.

HOCs add another component layer, which can make debugging and understanding props a little harder.

Also, never create a HOC inside another component's render function. It can cause React to treat the wrapped component as a new component and reset its state.

10. Lazy Loading and Code Splitting

Let's talk about performance. Imagine your React application has a dashboard, admin panel, settings page, reports, charts, and a rich text editor.

Does every user need all these features as soon as the application opens?

Probably not. So why load all their JavaScript at the beginning?

That's where Lazy Loading comes in. Lazy loading lets you load a component only when it's needed. React provides two useful features for this:

  • React.lazy()

  • Suspense

Example

Normally, you might import a component like this:

import Settings from "./Settings";

But you can load it lazily:

import { lazy, Suspense } from "react";

const Settings = lazy(() => import("./Settings"));

function App() {
  return (
    <Suspense fallback={<p>Loading settings...</p>}>
      <Settings />
    </Suspense>
  );
}

Now React can load the Settings component when it is first rendered. While the component is loading, users will see the fallback message.

You can use the same approach for:

  • Large dashboard pages.

  • Admin panels.

  • Charts and reports.

  • Rich text editors.

  • Large modals.

  • Features that users rarely open.

Which React Pattern Should You Use?

Now you know ten different React patterns. But here's the real question: Which one should you use in your project? You don't need to use all of them. Just look at the problem you're trying to solve. Here's a quick comparison:

React Pattern

What It Solves

Common Use Cases

Container and Presentational

Separates logic and UI

Product lists, dashboards

Custom Hooks

Reuses logic

Forms, API calls, browser events

Composition

Combines smaller components

Cards, layouts, UI libraries

Compound Components

Shares state between related components

Tabs, Accordions, Dropdowns

Controlled and Uncontrolled

Manages input values

Forms and search fields

Context API

Avoids prop drilling

Themes, authentication

Provider Pattern

Shares services and dependencies

API clients, logging

Render Props

Reuses behavior with custom UI

Flexible interactive components

Higher-Order Components

Adds features to existing components

Authentication, legacy code

Lazy Loading

Loads components when needed

Large pages and heavy features

My recommendation

If you're new to React, don't try to learn everything at once.

Start with:

  1. Composition: Learn how to build larger UIs from smaller components.

  2. Custom Hooks: Learn how to reuse logic.

  3. Controlled Components: Understand how React handles form inputs.

  4. Context API: Learn how to share data between components.

  5. Compound Components: Learn how to build flexible UI components.

These five patterns will give you a good starting point.

Later, you can explore HOCs, Render Props, Providers, and Lazy Loading when you actually need them.

Tags

# React# React Patterns# React Design Patterns# React Best Practices# React Hooks# React Components# React Architecture# JavaScript
Keep Reading

Related Articles

Continue your learning journey