2

Can anyone help me understand how functional cmp gets re-render whenever there is change in state.

refer below e.g.

function App() {
  const [count, updateCount] = useState(0);

  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={() => updateCount(count + 1)}>Update</button>
    </div>
  );
}

If I compare this with class based react component then over there we had render function inside class which I believe must be getting trigger whenever there is changes in state or props (there must be chain of life-cycle functions and one of them would be this.render())

But with above code structure App is a functional component and inside App we are changing state/count, how react get to know that after updateCount/setter function, App/(or its parent function) should get called again? I mean we are not passing reference of App function to useState right.

Manish
  • 21
  • 2
  • It hooks to internal react state. Like there is a hidden class behind every functional comonent. Check the FAQ https://reactjs.org/docs/hooks-faq.html#how-does-react-associate-hook-calls-with-components – UjinT34 Mar 20 '19 at 14:17
  • Related question: https://stackoverflow.com/questions/53974865/how-do-react-hooks-determine-the-component-that-they-are-for/53980190#53980190 – Ryan Cogswell Mar 20 '19 at 15:54

1 Answers1

0

Your code inside your render function REACTS to your state. People like to say that UI is a visual representation of your component's state.

Until Hooks release, there was no way to have React's internal state in function component. You could've been using Redux, MobX or some other third party lib to manage your state, but no way to connect to component's local state.

Your render function behaves exactly like it would in stateful class component,.

  • Question is about how react is re-rendering/invoking the functional component based on the hook which is inside of the same functional component – kgsnaidu May 21 '21 at 16:07