Srishti Gupta
Srishti Gupta

Reputation: 1273

Why React re-renders a component even when changed prop or state has no relation to JSX?

Why does React re-renders a component when its prop or state changes even though the changed prop or state has no relation to the returned JSX?

I read about React Reconciliation from the official documentation. It explains the diffing mechanism but not the need for re-rendering a component when the state has no visual impact on Virtual DOM tree.

Consider the trivial dummy code given below where myState is a state of the App component and it has no relation to the returned JSX but still if myState gets updated (which happens inside the buttonClickHandler, React re-renders the App component.

import React, { useState } from "react";
const App = () => {
  console.log("[App] rendered");

  const [myState, setMyState] = useState(false);

  const buttonClickHandler = () => {
    console.log("Button clicked!");
    setMyState((prevState) => !prevState);
  };

  return <button onClick={buttonClickHandler}>Click Me</button>;
};

export default App;

Upvotes: 0

Views: 38

Answers (1)

AKX
AKX

Reputation: 169398

Because React can't possibly know whether a state or prop change has an effect on the JSX before you return it.

Even if a component is rerendered, it doesn't mean it's re-reconciled into the real DOM (and indeed, if there are no changes, the DOM is left untouched).

If a function component's render is computationally heavy, you can use e.g. useMemo to memoize those heavy computations.

Upvotes: 1

Related Questions