How To Write Better Functional Components in React

How To Write Better Functional Components in React

5 Simple Tips For Readability and Optimization

Those of us who have worked with functional components in React know that the introduction of Hooks has made our lives a lot easier. However, functional components have their own set of complexities and gotchas. As a result, it can sometimes be difficult to write readable and optimized functional components. Today, we will look at five simple tips to help us do just that.

1. Memoize Complex Data

Let’s take a look at the following React component called SortedListView:

import React from 'react';

function SortedListView ({ title, items, comparisonFunc }) {
  const sortedItems = [...items];
  sortedItems.sort(comparisonFunc);
  return (
    <div>
      <h1> {title} </h1>
      <ul>
        {sortedItems.map(item => <li> {item} </li>)}
      </ul>
    </div>
  );
}

This component takes an array of items, sorts them according to the comparison function provided, and displays them. However, this sorting operation could take a large amount of time if the number of items is large or the comparison function is complicated. This could end up becoming a bottleneck because the component will re-sort the items on each re-render even if the items array or the comparisonFunc does not change, but some other prop or the state changes.

We can make this more CPU-efficient by memoizing the sorting operation and re-sorting only when the items array changes.

Update:

Memoizing can also help prevent unnecessary re-renders when objects generated in a parent component have to be passed to a child component (More on this in #2). However, for components under our own control, we can always prevent unnecessary re-renders. We can do this by avoiding passing objects to the dependency array of useEffect and other similar hooks.

To see a benchmark of the actual performance gains and performance trade-offs of useMemo, please take a look at the following link.

Should You Use useMemo in React? A Benchmarked Analysis.

Memoization can easily be accomplished with the useMemo Hook:

import React, { useMemo } from 'react';

function SortedListView ({ title, items, comparisonFunc }) {
  const sortedItems = useMemo(() => {
    const sortedItems = [...items];
    sortedItems.sort(comparisonFunc);
    return sortedItems;
  }, [items, comparisonFunc]);
  return (
    <div>
      <h1> {title} </h1>
      <ul>
        {sortedItems.map(item => <li> {item} </li>)}
      </ul>
    </div>
  );
}

So, we can use useMemo to memoize or cache results to expensive operations by trading off some memory. With that being said, you do not need to use useMemo in instances where the operations are not expensive or the object is not passed into any other component, as shown in the above link.

react-hook javascript react

What is Geek Coin

What is GeekCash, Geek Token

Best Visual Studio Code Themes of 2021

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? Also, we will see the react hooks example.

The Ugly Side of React Hooks

In this post, I will share my own point of view about React Hooks, and as the title of this post implies, I am not a big fan.

React Hooks Tutorial for Beginners: Getting Started With React Hooks

React hooks tutorial for beginners, learn React hooks step by step: Introduction, useState Hook, useState with previous state, useState with object, useState with array, useEffect Hook, useEffect after render, Conditionally run effects, Run effects only once, useEffect with cleanup, useEffect with incorrect dependency, Fetching data with useEffect, useContext Hook, useReducer Hook, useReducer, Multiple useReducers, useReducer with useContext, Fetching data with useReducer, useState vs useReducer, useCallback Hook, useMemo Hook, useRef Hook

Deep Dive into React Hooks

React Hooks are the newest addition to the React ecosystem starting with React 16.8. The basic form of React Hooks lets you use state and other React features without writing a class.