When does React call a component constructor function and what's like the execution flow?

Viewed 51

Say I have a simple component like this one:

export default function Foo({someProp}) {
  const a = Math.random();

  return <div>{a}{someProp}</div>
}

As far as I know, when someProp updates, React will trigger a re-render. Will it execute the whole Foo function once again and reassign const a a new random value? Will the value be displayed in the <div>? Thank you.

1 Answers

The answer for every one of your question is yes. A re-render is triggered when there is a props change as you said, and also when there is a state change. When re-rendering and also on the first render, everything behaves like in a normal JavaScript function, as far as assigning variables and everything else, except for some things related to React Hooks, like a state made with useState, a ref made with useRef...

Related