hjhku
hjhku

Reputation: 181

Why both button get re-render?

In the below program, as soon I click any button the other button also gets re-render even when I have used React.memo(). Also only other button gets re-render not the other count. why? I have a parent component like this:

import React, { useState } from 'react'
import Count from './Count'
import Button from './Button'
import Title from './Title'

function ParentComponent() {
    const [age, setAge] = useState(25)
    const [salary, setSalary] = useState(50000)

    const incrementAge = () => {
        setAge(age + 1)
    }

    const incrementSalary = () => {
        setSalary(salary + 1000)
    }

    return (
        <div>
            <Title />
            <Count text="Age" count={age} />
            <Button handleClick={incrementAge}>Increment Age</Button>
            <Count text="Salary" count={salary} />
            <Button handleClick={incrementSalary}>Increment Salary</Button>
        </div>
    )
}

export default ParentComponent

with 3 child components as below defined:

Title.js

import React from 'react'

function Title() {
  console.log('Rendering Title')
  return (
    <h2>
      useCallback Hook
    </h2>
  )
}

export default React.memo(Title)

Count.js

import React from 'react'

function Count({ text, count }) {
    console.log(`Rendering ${text}`)
    return <div>{text} - {count}</div>
}

export default React.memo(Count)

Button.js

import React from 'react'

function Button({ handleClick, children }) {
  console.log('Rendering button - ', children)
  return (
    <button onClick={handleClick}>
      {children}
    </button>
  )
}

export default React.memo(Button)

Upvotes: 1

Views: 65

Answers (1)

Yi Zhou
Yi Zhou

Reputation: 813

I will explain here

First, whenever you update your local state, your render function will re-run so all your child component will re-render

When you click age button, age button re-render because props change, salary button re-render because incrementSalary treat as new function if you not wrap with a useCallback, thus new props got passed to Button so it re-render

However your salary count component's props count={salary} never changed so react.memo will prevent it re-render.

Upvotes: 1

Related Questions