seongkuk han
seongkuk han

Reputation: 740

How does react know which components have been updated?

import React from 'react';

const App = () => {
  console.log('app render');

  return (
    <div>
      <Children />
    </div>
  );
};

const Children = () => {
  const [update, setUpdate] = React.useState(false);

  console.log('children render');

  return (
    <div>
      <button onClick={() => setUpdate(!update)}>update</button>
    </div>
  );
};

export default App;

Above code, at first, two messages are printed out 'app render' and 'children render.' Then, when I click the update button, a message is printed 'children render'.

I learned the following rules when I started to learn React at beginning.

  1. when props are updated
  2. when states are updated
  3. when the parent component is updated

I've been working on React Projects well since then. Today, somehow, I got a question.

How does react know which components have been updated?

setUpdate tells React that Children is updated?

I think I can understand that React can notice the props changing. because, if render functions are called, it means they can know whether props of their children are changed or not.

But I don't understand how react recognizes state-changing.

Upvotes: 0

Views: 197

Answers (1)

AJcodez
AJcodez

Reputation: 34176

The components form a tree. In the first render, the React framework renders from the root node. Any component functions that call useState will have the set state function registered and associated with the component instance. In the future, if you call a set state function, the React framework finds the associated component instance to re-render the sub-tree.

Upvotes: 2

Related Questions