React patterns are essential for building scalable and maintainable web applications. This guide will cover some common patterns used in React development.

Common React Patterns

1. Higher-Order Components (HOCs)

Higher-Order Components are reusable components that wrap another component and enhance its behavior.

function withExtraProps(WrappedComponent) {
  return function EnhancedComponent(props) {
    return <WrappedComponent {...props} extraProp="value" />;
  };
}

2. Render Props

Render props is a pattern where you pass a function as a prop to a component, which returns a component to render.

class ParentComponent extends React.Component {
  render() {
    return <ChildComponent render={() => <div>Child Content</div>} />;
  }
}

3. Hooks

Hooks are functions that let you "hook into" React state and lifecycle features from function components.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

4. Context

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

import React, { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

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

function Toolbar() {
  const theme = useContext(ThemeContext);
  return (
    <div>
      <h1>My App</h1>
      <ThemeDisplay theme={theme} />
    </div>
  );
}

5. Component Lifecycle

React components have several lifecycle methods that you can use to perform actions at specific times in a component's life.

class Counter extends React.Component {
  componentDidMount() {
    console.log('Component did mount');
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('Component did update');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  render() {
    return <div>{this.props.count}</div>;
  }
}

Learn More

For more information on React patterns, check out our React Patterns Deep Dive.

React Patterns