When a component re-renders as a result of calling the state setter function returned by useState, does the entire function component get called again or only parts of the function component get called?
function MyComponent() {
let [count, setCount] = useState(0);
const handleChange = () {
setCount((prevCount) => prevCount 1)
}
return (
<p onClick={handleChange}>
Count = {count}
</p>
)
}
In the above example, when we click the paragraph element, handleChange()
gets called which in turn calls the state setter function setCount()
. This causes our component to re-render. But when the component re-renders( or the function MyComponent gets called), the useState(0)
function gets called again. This should set the initial value of count
to 0 again. So shouldn't the counter be stuck at 0 instead of progressing to 1, 2, 3 and so on?
CodePudding user response:
Let say your component tree has parent and has children called childOne and childtwo. if you change the state of the ChildOne;Only the ChildOne get rendered, Not Parent and childtwo get rendered. But if you change the state of the parent, whole component tree get retendered
CodePudding user response:
Whole functional component will be rerendered. If the props value which you are passing to the child component is not changing then you can prevent the rerendering of child component by using React.memo
CodePudding user response:
This is the idea of hooks. They use closures.
If it was let count = 0
, then yes, if would reset to 0, this is why it is let [count] = useState(0)
The whole thing gets re-render and everything is getting re-calculated.
The argument you pass in useState / useRef is used only once, when the component mounts. If it is expensive operation, it recalculate on each render (there are ways to improve this), but the value of it is used only once. Then when you call setState it updates the value.
They work like this:
let ref = {};
const useRef = (defaultValue) => {
if (!ref.current) {
ref.current = defaultValue
}
return ref
}
The hook argument is used only once.