Sobes.tech
Junior — Senior

Identifying components that re-render when a button is clicked in React

livecode

Task condition

It is necessary to determine which parts of the interface will be re-rendered after clicking the Render button and explain the reasons for such re-rendering.

import React from 'react';

export default function App() {
  const forceUpdate = useForceUpdate();
  return (
    <div style={{ margin: '20px', padding: '20px', border: '2px solid green' }}>
      <button onClick={forceUpdate}>Render</button>
      <RenderCount />
      <Parent />
    </div>
  );
}

const Parent = () => {
  const [value, setValue] = React.useState('');
  const handleChange = (e) => {
    setValue(e.target.value);
  };
  return (
    <form style={{ margin: '20px', padding: '20px', border: '2px solid blue' }}>
      Input value is: {value}
      <RenderCount />
      <Child onChange={handleChange} />
    </form>
  );
};

const Child = ({ onChange }) => {
  return (
    <div style={{ padding: '20px', margin: '20px', border: '2px solid red' }}>
      <input type="text" name="value" onChange={onChange} />
      <RenderCount />
    </div>
  );
};

function RenderCount() {
  const renderCount = React.useRef(1);
  React.useEffect(() => {
    renderCount.current += 1;
  });
  return (
    <div style={{ marginTop: '10px' }}>
      Render count: {renderCount.current}
    </div>
  );
}

Questions for analysis:

  • Which components will receive a new render after calling forceUpdate?
  • Why might Parent and Child re-render or not?
  • How does the RenderCount hook work and how does it reflect the number of renders?
  • What optimizations (e.g., React.memo) could change the behavior?