79221938

Date: 2024-11-25 06:51:04
Score: 1
Natty:
Report link

a. React will render for the first change.

b. React will render for repeating the same value.

c. However, React will not render any more for any more repetition of the same value.

Example,

a. Changing a state from null to the text 'a' - Component will render.
b. Setting the state with the same text 'a' - Component will render.
c. Setting the state with the same text 'a' - Component will  NOT render.
d. Setting the state with the same text 'a' - Component will  NOT render.

The sample code shows the same.

App.js

import { useState } from 'react';

export default function App() {
  const [text, setText] = useState(null);

  console.log(`state changed ${text}`);
  return (
    <>
      The state is {text}
      <br />
      <button onClick={() => setText('a')}>Set state to the text 'a'</button>
      <br />
      <button onClick={() => setText('a')}>Set state to the text 'a'</button>
      <br />
      <button onClick={() => setText('a')}>Set state to the text 'a'</button>
      <br />
      <button onClick={() => setText('a')}>Set state to the text 'a'</button>
    </>
  );
}

Trial run

Browser display - after clicking all four buttons, the component rendered for 3 times only including initial render. Two renders have been skipped

Browser display - after clicking all four buttons

Coming to your question:

Question 1

expect(result.current.renderCount).toBe(4); // why also 4? I am expecting 3

You are getting 4 over here, as we have discussed above, React will render for the first repetition of the change. Therefore the two state update with the text 'a' will be counted here.

Question 2

expect(result.current.renderCount).toBe(4); // why still 4? if it was queueing it should be 6

It gives 4, since it ignores the 3rd and 4th repetition of the text 'a'.

For more about this, kindly see a similar question and its discussion over here. Why does it re-render even when state is same?

For a comprehensive documentation on this topic, kindly refer to the document here, Blogged Answers: A (Mostly) Complete Guide to React Rendering Behavior

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Me too answer (2.5): see a similar question
Posted by: WeDoTheBest4You