skip to Main Content

This is my Parent Component , I am using react.memo and usecallback so that i do no un-necessarily re-render component on every button click ,
Instead I am getting these many logs
Rendering Title

Title.js:4 Rendering Title

Count.js:4 Rendering Age

Count.js:4 Rendering Age

Button.js:4 Rendering button – Increment Age

Button.js:4 Rendering button – Increment Age

Count.js:4 Rendering Salary

Count.js:4 Rendering Salary

Button.js:4 Rendering button – Increment Salary

Button.js:4 Rendering button – Increment Salary

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

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

  const incrementAge = useCallback(() => {
    setAge(age + 1);
  }, [age]);

  const incrementSalary = useCallback(() => {
    setSalary(salary + 1000);
  }, [salary]);

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

export default ParentComponent;

Titlle.js

import React from 'react';

function Title() {
  console.log("Rendering Title");
  return (
    <div>Title</div>
  );
}

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'
//children -- props.children -- Increment age -- 
function Button({handleClick , children}) {
  console.log('Rendering button - ', children)
    return (
    <button onClick={handleClick}>{children}</button>
  )
}

export default React.memo(Button); 

2

Answers


  1. I ran your code and it is running as expected, no additional logs, only getting increment and decrement function logs.

    Check your code – https://codesandbox.io/p/sandbox/elastic-chebyshev-3s9yzc?file=%2Fsrc%2FParentComponent.js%3A24%2C15-24%2C26

    Login or Signup to reply.
  2. Please make sure that your component is wrapped around StrictMode. Usually strict mode causes this behaviour in our react apps. If so, please remove it and try again.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search