iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📌

A Summary of Techniques to Prevent Re-renders in React

に公開
2022/11/06

About this article

I have scrapped the mechanism of React re-rendering and how to suppress it in the following link.
Since I've done it, I'll summarize it here in an article.
https://zenn.dev/ishiyama/scraps/f5b25b3a608bdc

How to check for re-renders

By using Chrome Developer Tools, you can see when re-rendering is occurring.
The outer frame of the relevant part glows to indicate it is being re-rendered. Also, the color of the frame turns to yellow as the load increases.

Basics of re-rendering

In React Hooks, when a State defined within a component is updated, that component is re-rendered.
If that component has several child components, all of them will also be re-rendered.

Input component

This is the Input component used in the following sections.
It basically just wraps the input tag, so you can skip it if you want to keep reading.

Input.tsx
export type InputProps = Omit<JSX.IntrinsicElements["input"], "ref"> & {
  inputRef?: React.Ref<HTMLInputElement>
}

export const Input = ({ inputRef, ...props }: InputProps) => {
  return (
    <div style={{ margin: 10 }}>
      <input {...props} ref={inputRef} />
    </div>
  )
}

useState

Using useState straightforwardly looks like this.

import { useState } from "react"
import { HeavyComponent } from "../../../components/HeavyComponent"
import { Input } from "../../../components/Input"

const Page = () => {
  const [input1, setInput1] = useState("")
  const [input2, setInput2] = useState("")

  const handleChange1 = (e: React.ChangeEvent<HTMLInputElement>) =>
    setInput1(e.target.value)

  const handleChange2 = (e: React.ChangeEvent<HTMLInputElement>) =>
    setInput2(e.target.value)

  return (
    <div>
      <Input value={input1} onChange={handleChange1} />
      <Input value={input2} onChange={handleChange2} />
      <small>{JSON.stringify({ input1, input2 })}</small>
      <HeavyComponent />
    </div>
  )
}

export default Page

You can see that all components are re-rendered with every input, and the load increases.
If you continue building in this state, it will cause the screen to stutter.

React.memo

Memoize the component.
A memoized component will not be re-rendered as long as the values of the props it depends on remain unchanged.

import { memo, useState } from "react"
import { HeavyComponent } from "../../../components/HeavyComponent"
import { Input, InputProps } from "../../../components/Input"

const InputMemo = memo((props: InputProps) => <Input {...props} />)
const HeavyComponentMemo = memo(() => <HeavyComponent />)

const Page = () => {
  const [input1, setInput1] = useState("")
  const [input2, setInput2] = useState("")

  const handleChange1 = (e: React.ChangeEvent<HTMLInputElement>) =>
    setInput1(e.target.value)

  const handleChange2 = (e: React.ChangeEvent<HTMLInputElement>) =>
    setInput2(e.target.value)

  return (
    <div>
      <InputMemo value={input1} onChange={handleChange1} />
      <InputMemo value={input2} onChange={handleChange2} />
      <small>{JSON.stringify({ input1, input2 })}</small>
      <HeavyComponentMemo />
    </div>
  )
}

export default Page

(It might be difficult to see, but re-rendering is suppressed only for HeavyComponent.)

useCallback

While re-rendering of HeavyComponent is suppressed, the text boxes are still re-rendered every time.

This is because handleChange1 and 2 are recreated every time the Page itself is re-rendered when the state is updated. It's a basic concept, but even if the logic is the same, redefining a function makes it a different function.

Use useCallback to suppress the re-definition of functions. With useCallback, you can prevent the re-definition of functions as long as there are no changes in the dependencies specified in the second argument.

import { memo, useCallback, useState } from "react"
import { HeavyComponent } from "../../../components/HeavyComponent"
import { Input, InputProps } from "../../../components/Input"

const InputMemo = memo((props: InputProps) => <Input {...props} />)
const HeavyComponentMemo = memo(() => <HeavyComponent />)

const Page = () => {
  const [input1, setInput1] = useState("")
  const [input2, setInput2] = useState("")

  const handleChange1 = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => setInput1(e.target.value),
    []
  )

  const handleChange2 = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => setInput2(e.target.value),
    []
  )

  return (
    <div>
      <InputMemo value={input1} onChange={handleChange1} />
      <InputMemo value={input2} onChange={handleChange2} />
      <small>{JSON.stringify({ input1, input2 })}</small>
      <HeavyComponentMemo />
    </div>
  )
}

export default Page

Constants

Items defined outside of the component are not subject to re-definition even when a re-render occurs. It is good practice to define constants or things that do not depend on state outside of the component.

const invokeLog = () => console.log("")

const Page = () => {
...

useRef

The text box being typed in is still being re-rendered. To suppress all re-renders, use useRef.
In addition to DOM manipulation, useRef has the function of holding state. When controlling input elements with ref, the state is not updated upon input, so all re-renders can be suppressed.
You can retrieve the values at specific timings, such as during submission, to use the input data. Conversely, it is not suitable for displaying changes on the screen in real-time.

import { memo, useRef, useState } from "react"
import { HeavyComponent } from "../../../components/HeavyComponent"
import { Input, InputProps } from "../../../components/Input"

const InputMemo = memo((props: InputProps) => <Input {...props} />)
const HeavyComponentMemo = memo(() => <HeavyComponent />)

const Page = () => {
  const input1Ref = useRef<HTMLInputElement>(null)
  const input2Ref = useRef<HTMLInputElement>(null)

  const [values, setValues] = useState({ input1: "", input2: "" })

  const submit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setValues({
      input1: input1Ref.current?.value ?? "",
      input2: input2Ref.current?.value ?? "",
    })
  }

  return (
    <form onSubmit={submit}>
      <InputMemo inputRef={input1Ref} />
      <InputMemo inputRef={input2Ref} />
      <small>{JSON.stringify(values)}</small>
      <HeavyComponentMemo />
      <button>submit</button>
    </form>
  )
}

export default Page

React Hook Form (RHF)

RHF performs control via ref. RHF's register function returns name, ref, onBlur, and onChange.
Therefore, by using RHF, re-renders are suppressed without you even realizing it, making performance lags less likely to occur. (Wonderful👏)

import { memo, useState } from "react"
import { SubmitHandler, useForm, UseFormRegisterReturn } from "react-hook-form"
import { HeavyComponent } from "../../../components/HeavyComponent"
import { Input } from "../../../components/Input"

const HeavyComponentMemo = memo(() => <HeavyComponent />)

type FormValues = {
  input1: string
  input2: string
}

const Page = () => {
  const { register, handleSubmit } = useForm<FormValues>()

  const [state, setState] = useState({ input1: "", input2: "" })

  const submit: SubmitHandler<FormValues> = (data) => setState(data)

  return (
    <form onSubmit={handleSubmit(submit)}>
      <Input {...convert(register("input1"))} />
      <Input {...convert(register("input2"))} />
      <small>{JSON.stringify(state)}</small>
      <HeavyComponentMemo />
      <button>submit</button>
    </form>
  )
}

// Since inputRef is defined instead of ref in Input.tsx, reset ref to inputRef.
function convert({ ref, ...others }: UseFormRegisterReturn) {
  return { inputRef: ref, ...others }
}

export default Page

Notes on memoization

Memoizing everything is a bad practice.
Memoization itself comes with a cost. Therefore, it is best to limit memoization to components with high rendering costs.

Source

The code used is stored here:
https://github.com/ishiyama0530/react-form-recipes/tree/main/src/pages/rerendering

Summary

Using memoization or refs for everything increases the amount of code, which in turn reduces readability.
There is also a cost associated with processing them.
It is important to find a balance in your implementation regarding how far to go with these optimizations.

Discussion