January 28, 2022

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

3 React Component Design Patterns You Should Know About


React is arguably the most popular JavaScript library for building user interfaces and one reason for this is its unopinionated nature. Whether you choose to see React as a framework or library, one thing that can be agreed on is its hands-off approach to how developers should build react applications, which gives developers and developer teams the freedom to decide how they want their applications to be made. After working on different React applications with different teams and studying other React applications built, you notice some common design patterns.

In this article, we will be looking at three popular design patterns for building React applications.

1. Presentational and Container Component Pattern

This is a pattern coined by Dan Abramov. In this pattern, components are divided into:

  • Presentation Components: These are components that are responsible for how the UI looks. They don’t have any dependencies with any part of the application and are used to display data. An example is a list:

1const ItemsList = (props) => {

2 return (

3 <ul>

4 {props.items.map((item) => (

5 <li key={item.id}>

6 <a href={item.url}>{item.name}</a>

7 </li>

8 ))}

9 </ul>

10 );

11};

In the example above, our ItemsList component is only responsible for displaying the data passed as props on the User interface. Presentational components are also called Stateless functional components but can also be written as class components and can contain state that relates to the UI

1class TextInput extends React.Component {

2 constructor(props) {

3 super(props);

4 this.state = {

5 value: ""

6 };

7 }

8 render() {

9 return (

10 <input

11 value={this.state.value}

12 onChange={(event) => this.setState({ value: event.target.value })}

13 />

14 );

15 }

16}

In the example above, we’ve created a Presentational class component, TextInput, responsible for managing its state.

  • Container Components: Unlike presentational components, Container components are more responsible for how things work. They are usually class components that contain lifecycle methods and Presentational components. It is also where data fetching happens.

1class TvShowsContainer extends React.Component {

2 constructor(props) {

3 super(props);

4 this.state = {

5 shows: [],

6 loading: false,

7 error: ""

8 };

9 }

10 componentDidMount() {

11 this.setState({ loading: true, error: "" });

12 fetch("https://api.tvmaze.com/schedule/web?date=2020-05-29")

13 .then((res) => res.json())

14 .then((data) => this.setState({ loading: false, shows: data }))

15 .catch((error) =>

16 this.setState({ loading: false, error: error.message || error })

17 );

18 }

19 render() {

20 const { loading, error, shows } = this.state;

21 return (

22 <div>

23 <h1> Tv Shows </h1>

24 {loading && <p>Loading...</p>}

25 {!loading && shows && <ItemsList items={shows} />}

26 {!loading && error && <p>{error}</p>}

27 </div>

28 );

29 }

30 }

We’ve created a TvShowsContainer component that fetches data from an API when the component mounts in the example above. It also passes that data to the presentational component ItemsList we created earlier. The advantage of this pattern is the separation of concerns and component reusability. Other Container components can reuse the ItemList presentational component to display data since it isn’t tightly coupled with the TvShowsListContainer. You can view the working application here.

Do note that Dan also mentions that he’s no longer promoting this pattern as he’s changed his view on the matter since he originally coined it. However, you might find it useful for your particular use case which is why I thought it relevant to be mentioned on this list.

2. Provider Pattern

One major problem faced by React developers is Prop drilling. Prop drilling is a scenario in which data(props) is passed down to different components until it gets to the component where the prop is needed. While prop-drilling isn’t bad, it becomes a problem when unrelated components share data which brings us to the Provider pattern. The Provider pattern allows us to store data in a central location, e.g. React Context object and the Redux store. The Context Provider/Store can then pass this data to any component that needs it directly without drilling props.

Imagine implementing dark mode for a web app and making unrelated components respond to a theme change triggered by a different component. We can achieve that using the Provider pattern. We create a React context object for storing the value of the theme.

1import { createContext } from "react";

2const ThemeContext = createContext({

3 theme: "light",

4 setTheme: () => {}

5});

6export default ThemeContext;

In the App.js file, we wrap imported components with ThemeContext.Provider. This gives the different components, and their children access to the Context object created

1import React, { useState, useMemo } from "react";

2import Header from "./Header";

3import Main from "./Main";

4import ThemeContext from "./context";

5import "./styles.css";

6export default function App() {

7 const [theme, setTheme] = useState("");

8 const value = useMemo(() => ({ theme, setTheme }), [theme]);

9 return (

10 <ThemeContext.Provider value={value}>

11 <div className="container">

12 <Header />

13 <Main />

14 </div>

15 </ThemeContext.Provider>

16 );

17}

By default, the ThemeContext is stateless and can’t be updated. To solve this, we can connect the ThemeContext to a state and provide an update function in the ThemeContext to modify the state.

To access ThemeContext in the components, we can make use of the useContext hook introduced in React 16.9

1import { useContext } from "react";

2import ThemeContext from "./context";

3const Header = () => {

4 const { theme, setTheme } = useContext(ThemeContext);

5 const toggleTheme = () => {

6 if (theme === "dark") {

7 setTheme("");

8 return;

9 }

10 setTheme("dark");

11 return;

12 };

13 return (

14 <header className={theme === "dark" && "dark"}>

15 <h1> Tv Shows </h1>

16 <button onClick={toggleTheme}>Toggle Theme</button>

17 </header>

18 );

19};

20export default Header;

21

22

23import { useContext } from "react";

24import ThemeContext from "./context";

25const Main = () => {

26 const { theme } = useContext(ThemeContext);

27 return (

28 <main className={theme === "dark" && "dark"}>

29 <h2>

30 {" "}

31 {theme === "dark" ? "Dark theme enabled" : "Light theme enabled"}

32 </h2>

33 </main>

34 );

35};

36export default Main;

While Context makes it easier to pass data among components, it is advised to use this approach sparingly because it makes component reuse difficult. You can access the working app of the example above here. The Provider pattern is used in React Router and React-Redux.

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue.
It’s like having your browser’s inspector open while looking over your user’s shoulder.
OpenReplay is the only open-source alternative currently available.

Happy debugging, for modern frontend teams – Start monitoring your web app for free.

3. Compound Components Pattern

Compound components are components that share a state and work together to achieve a common goal. An example is the <select> and <option> HTML element. When combined, they create a drop-down menu, but they don’t achieve much on their own.

The Compound Components pattern is used in popular React UI libraries, e.g. Ant Design and Material UI. Below is an implementation of the Menu component in Material UI

1import * as React from 'react';

2import Menu from '@mui/material/Menu';

3import MenuItem from '@mui/material/MenuItem';

4

5export default function MaterialMenu() {

6 return (

7 <div>

8 <Button> Menu </Button>

9 <Menu>

10 <MenuItem>Profile</MenuItem>

11 <MenuItem>My account</MenuItem>

12 <MenuItem>Logout</MenuItem>

13 </Menu>

14 </div>

15 );

16}

Without compound components, we will have had to pass props to the parent component, and then the parent component passes the data down to child components

1<Menu items={['Profile','My account', 'Logout']} />

The above looks simple, but we start having problems passing more props down to the child component. For example, imagine we wanted a default selected menu item

1<Menu items={['Profile','My account', 'Logout']} defaultSelected={1} />

As more requirements come in, the component starts becoming messy and unusable. The compound component pattern provides a cleaner way of achieving this.

There are two ways to build a React component using the compound component pattern approach:

  • React.cloneElement
  • React Context

I’ll be using the React Context approach for the example below

1import {

2 createContext,

3 useState,

4 useCallback,

5 useMemo,

6 useContext

7} from "react";

8import "./styles.css";

9const MenuContext = createContext();

10const Menu = ({ children, defaultSelected }) => {

11 const [selectedItem, setSelectedItem] = useState(defaultSelected);

12 const toggleSelectedItem = useCallback(

13 (item) => {

14 if (item !== selectedItem) {

15 setSelectedItem(item);

16 return;

17 }

18 selectedItem("");

19 },

20 [selectedItem, setSelectedItem]

21 );

22 const value = useMemo(

23 () => ({

24 toggleSelectedItem,

25 selectedItem

26 }),

27 [toggleSelectedItem, selectedItem]

28 );

29 return (

30 <MenuContext.Provider value={value}>

31 <menu className="menu">{children}</menu>

32 </MenuContext.Provider>

33 );

34};

We’ve created a context object, MenuContext, for the Menu component using the createContext function provided by the React Context API. This will hold the shared state for the Menu and MenuItem components. We’ve also created a state for a selected menu item. This will allow us to update the context similar to what we did in the Provider Pattern since the Context API is stateless by design.

The next step is building the MenuItem Component.

1const useMenuContext = () => {

2 const context = useContext(MenuContext);

3 if (!context) {

4 throw new Error(

5 "Menu item component cannot be used outside the Menu component."

6 );

7 }

8 return context;

9};

10const MenuItem = ({ value, children }) => {

11 const { toggleSelectedItem, selectedItem } = useMenuContext();

12 return (

13 <button

14 onClick={() => toggleSelectedItem(value)}

15 id={`${value}-menu-item`}

16 className={`menu__item ${selectedItem === value && "active"}`}

17 >

18 {children}

19 </button>

20 );

21};

The first thing done here is creating a custom hook useMenuContext for checking if the MenuItem is used outside the Menu component and throwing an error if that happens. After that, we create our MenuItem utilising the shared state with the Menu component to detect what style to apply to a selected MenuItem and change the selected item when a menu item is clicked.

To wrap up, we connect these components together in the App component

1export default function App() {

2 return (

3 <Menu defaultSelected="My account">

4 <MenuItem value="Profile">Profile</MenuItem>

5 <MenuItem value="My account">My account</MenuItem>

6 <MenuItem value="Logout">Logout</MenuItem>

7 </Menu>

8 );

9}

You can view the complete app here

Conclusion

In this article, we’ve looked at various design patterns to use in building React components that are extensible and reusable. While this is not an exhaustive list, it applies to most problems you will probably encounter when building components.



Source link