React Design Patterns

React Design Patterns

Hello developers!! While developing apps in React, I'm sure you have come across different use cases which cannot be easy to solve using the same older approach.

Each use cases demand a different pattern to solve the problem in the most optimised way and also made our code more scalable.

React provides different design patterns to solve common problems. The list of commonly used design patterns in React are:

  • Presentational & Container Component

  • Higher Order Components

  • Render Props

  • Compound Components

  • Hooks

Let's explore them one by one.

🎯 1. Presentational & Container Component

Each component in React has two parts: One is logic to handle your data and the other is displaying data on screen.

This pattern helps separate concerns by splitting components into two categories. Container components handle the logic and state management, while Presentational components focus on rendering the UI based on the provided props.

export const DisplayList = ({ patientRecord }) => {
  return (
    <ul>
      {patientRecord.map((patient, id) => {
        return <li key={id}>{patient}</li>;
      })}
    </ul>
  );
};

Container components, on the other hand, keep track of the internal states and data-fetching logic and handles business logic.

export const PatientComponent = () => {
  const [patientList, getPatientList] = React.useState([]);

  React.useEffect(() => {
    // Fetch data through an API and apply business logic
    (async () => {
      const response = await fetchPatientList();

      setPatientList([...response]);
    })()
  }, []);

  // provide data to presentational component to display
  return <DisplayList patientRecord={patientList} />; 
};

The container component passes the state and any required callbacks as props to the presentational component. The presentational component is responsible for rendering the UI based on the provided props, without worrying about the data fetching or business logic.

🎯 2. Higher Order Components

HOCs take one component as an input and give a newly created component with additional functionalities as an output. It allows you to reuse component logic by wrapping components with additional functionality.

By using HOCs, we can easily add common functionality to multiple components without duplicating code.

import React from 'react';

function withLogging(WrappedComponent) {
  return function WithLogging(props) {
    React.useEffect(() => {
      console.log(`Component ${WrappedComponent.name} mounted`);
      return () => {
        console.log(`Component ${WrappedComponent.name} unmounted`);
      };
    }, []);

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

// Usage
const MyComponent = (props) => {
  return <div>My Component</div>;
};

const EnhancedComponent = withLogger(MyComponent);

In the example above, withLogger is a HOC that takes a component (WrappedComponent) as input and returns a new component (WithLogger). The returned component logs a message to the console when it mounts and unmounts.

To use the HOC, we wrap our original component MyComponent with withLogger, creating a new component EnhancedComponent. The enhanced component has the same functionality as MyComponent, but it also includes the logging behaviour defined in the HOC.

🎯 3. Render props

In this pattern, a component receives a function as a prop and uses that function to render its content.

import React from 'react';

const MouseTracker = (props) => {
  const [position, setPosition] = React.useState({ x: 0, y: 0 });

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

  return <div onMouseMove={handleMouseMove}>{props.renderPosition(position)}</div>;
};

// Usage
const DisplayMousePosition = () => (
  <MouseTracker
    renderPosition={({ x, y }) => (
      <div>
        Mouse position: {x}, {y}
      </div>
    )}
  />
);

A prop like renderPosition is called a render prop because it is a prop that specifies how to render a piece of the user interface.

🎯 4. Compound Components

Compound components are a pattern used in React to create components that work together as a group, allowing users to customize and control the rendering of multiple related components.

It allows you to define a parent component that encapsulates the behaviour and state of child components, while still giving flexibility to users to determine the composition and appearance of the child components.

Let's consider a use case where you need to create a List component in React which looks something like an unordered list in native HTML or an Accordion component.

<List>
 <ListItem>1</ListItem>
 <ListItem>2</ListItem>  
 <ListItem>3</ListItem>
 <ListItem>4</ListItem> 
</List>

Now in this scenario, we need some of the states of the List component to be transferred to its child component i.e. ListItem. It can be implemented either by using the context API or React.cloneElement API.

Let's explore how to develop the same scenario using Context API.

const ListContext = React.createContext();
const { Provider } = ListContext;

// Parent Component
export const List = (props) => {
  const { children, size } = props;

  const sharedProp = { size }

  return (
    <Provider value={sharedProp}>
      <ul>
        {children}
      </ul>  
    </Provider>
  )
}

// Child Component
export const ListItem = (props) => {
  const contextProp = React.useContext(ListContext);
  const { size } = contextProp;

  return (
   <li className={size === 'medium' ? bg-primary : bg-secondary}>
      {props.children}
   </li>
  )
}

// Usage
<List size='medium'>
 <ListItem>Item 1</ListItem>
 <ListItem>Item 2</ListItem>
 <ListItem>Item 3</ListItem>
</List>

In the above example, React Context is created to share the prop size between the parent (<List>) and child (<ListItem>) components. Also, the user has the flexibility to provide custom content inside each list item.

🎯 5. Hooks

Hooks are introduced in React Functional component as a replacement for Class components. There are multiple hooks available to manage states and different lifecycle methods of React.

import React, { useState } from 'react';

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

  return (
    <Button onClick={() => setCount(count + 1)}></Button>
  )
}

We can also create custom hooks to solve our specific use case and code reusability.

You can read about the most commonly used built-in react hooks here.

🎯 Wrap Up!!

That's all for this article. Thank you for your time!! Let's connect to learn and grow together. LinkedIn Twitter Instagram

Buy-me-a-coffee