Introduction

With its incredible capabilities, React has overlapped the old-school CSS, HTML, and JavaScript offering ease of coding. The JavaScript library works with virtual DOM concepts and an exclusive range of developer tools instead of just manipulating the DOM.
Developers usually run out of ideas with new concepts and ideas while coding. If you’re one of those looking to revamp your React skills, you must utilize React Design Patterns. Let’s explore them all!

6 Most Useful React Design Patterns to Try

Container Components

First and foremost, the container components pattern leads the list with its elite diversification functionality. It’s designed to separate data fetching/logic and events from the presentational components.
As the presentational components are dumb components, they just render the data fetched and passed by the container component. Take a look at the example displaying the container component pattern for a movie app using React hooks.

import { useEffect, useState } from 'react';
import { movies } from '../data/movies';
import './movies.css';

const fetchMovies = () => {­­­
  return movies;
};­­­

const MovieContainer = () => {
  console.log(fetchMovies());

  const [movies, setMovies] = useState([]);

  useEffect(() => {
    const movies = fetchMovies();
    console.log('MovieContainer: useEffect: movies: ', movies);
    setMovies(movies);
  }, []);

  return(
    <div className="movie-container">
      <h2>Movies</h2>
      <ul className ="movie-list">
        {movies.map(movie => (
          <li key={movie.id} className="movie">
            <img src={movie.poster} alt={movie.title} />
            <p>{movie.title} by {movie.director} was released on {movie.year}</p>
            <p>Rating: {movie.rating}</p>
          </li>
        ))}
      </ul>      
    </div>
  );
};

export default MovieContainer;
Render Props

In addition to conditional components, using render props can also be a great bet if you experience logic repetition. This pattern works with Prop which is equal to a function allowing you to share code between React components.
With render props, you can enable a component to toggle visibility and render its content. Take a look at the below example for an expansive view!

function Toggle({ children }) {
  const [isVisible, setIsVisible] = useState(false);

  function handleClick() {
    setIsVisible(!isVisible);
  }

  return children({
    isVisible,
    toggle: handleClick
  });
}
Conditional Rendering

Conditional rendering is an ultimate technique designed to render specific UI components according to certain factors such as user input, component state, and more. If you’re looking to implement a conditional rendering pattern in React, you can do it with the ternary operator, Logical && Operator, and switch statements.
Here’s how you can do it!

Ternary Operator
import React from "react";
function Greeting ()
{
  const isLoggedin = 'true'
  return (
      <div>
        {isLoggedin ? (<h1>Welcome back, User</h1>) : (<h1>please login to continue</h1>)}
      </div>
  )
}
export default Greeting
Logical && Operator
function ExampleComponent(props) {
  const isLoggedIn = props.isLoggedIn;
  return (
    <div>
      {isLoggedIn && <p>Welcome back, user!</p>}
      {!isLoggedIn && <p>Please login to continue.</p>}
    </div>
  );
}
Switch Statements
function ExampleComponent(props) {
  const status = props.status;
  switch (status) {
    case "loading":
      return <LoadingIndicator />;
    case "error":
      return <ErrorMessage message={props.errorMessage} />;
    case "success":
      return <SuccessMessage message={props.successMessage} />;
    default:
      return null;
  }
}
Context API

If we just dig into the default functionalities, React is set to pass props through every level of the component tree to pass data to a child component. With Context API, you can pass data at any level of the component tree without passing the props.
The process to use React Context API starts with creating a context object with the createContext function. After this, it will allow you to use the provider component to take value prop for any type of data. Let’s make it work!


import React from 'react';
import ReactDOM from 'react-dom';
import MyContext from './MyContext';

function App() {
  const data = { name: 'John', age: 30 };

  return (
    <MyContext.Provider value={data}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

function ChildComponent() {
  return (
    <MyContext.Consumer>
      {value => (
        <div>
          <p>Name: {value.name}</p>
          <p>Age: {value.age}</p>
        </div>
      )}
    </MyContext.Consumer>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
HOCs

Higher Order Components (HOCs) are JavaScript functions designed to add data and functionality to the component. They enable the reuse of component logic and allow you to share standard functionality between multiple components.
Moreover, the best part is the HOC pattern doesn’t require duplicating the code to add functionalities to components. Just create a Hoc.js file with the following code:

import React from "react";
const Hoc = (WrappedComponent, entity) => {
  return class extends React.Component {
    state = {
      data: [],
      term: "",
    };
    componentDidMount() {
      const fetchData = async () => {
        const res = await fetch(
          `https://jsonplaceholder.typicode.com/${entity}`
        );
        const json = await res.json();
        this.setState({ ...this.state, data: json });
      };
      fetchData();
    }
    render() {
      let { term, data } = this.state;
      let filteredData = data.slice(0, 10).filter((d) => {
        if (entity === "users") {
          const { name } = d;
          return name.indexOf(term) >= 0;
        }
        if (entity === "todos") {
          const { title } = d;
          return title.indexOf(term) >= 0;
        }
      });
      return (
        <div>
          <h2>Users List</h2>
          <div>
            <input
              type="text"
              value={term}
              onChange={(e) =>
                this.setState({ ...this.state, term: e.target.value })
              }
            />
          </div>
          <WrappedComponent data={filteredData}></WrappedComponent>
        </div>
      );
    }
  };
};
export default Hoc;

Hooks

Lastly, you have React Hooks as the most appreciated React Design Patterns. The pattern was introduced with React 16.8 update to enable developers to use React without any classes. Interestingly, you get over 15 pre-built React hooks in the library including Effect Hook and State Hook.
Even if you’re looking for a custom hook, you can create your own hook from scratch or just modify the existing one according to your needs. Here we get you an example of using the useState hook known for tracking state in a function component.

import { useState } from 'react';

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

  return (
    <>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </>
  );
}
Conclusion

React has emerged as an essential part of today’s web development, offering versatile features that provide developers with an improved coding experience. However, it poses innate challenges while executing practical experiments.
Solving these issues involves a great deal of attention and experimentation to understand modern design patterns and frameworks. Utilizing React Design Patterns is a great way to gain more insight into your projects and build cross-platform applications with ease.
With its well-structured templates and online libraries, you have all the tools at your disposal to make the process much simpler. And if used correctly, you’ll soon be able to gain the insights needed to become a top React developer.

Leave details and I will get back to you