I’m a little confused on when exactly rerender happens with functional component (i.e. hooks).
module GrandChildren = {
[@react.component]
let make = () => {
<div> {React.string("Children")} </div>;
};
};
module Children = {
[@react.component]
let make = (~active: bool) => {
<div>
{React.string("Children")}
{active ? React.string("Active") : React.string("Inactive")}
<GrandChildren />
</div>;
};
};
[@react.component]
let make = () => {
let (active, setActive) = React.useState(() => false);
let (pactive, setPActive) = React.useState(() => false);
<div>
<button
onClick={ev => {
ReactEvent.Mouse.preventDefault(ev);
setActive(v => !v);
}}>
{React.string("Toggle Child Active")}
</button>
<button
onClick={ev => {
ReactEvent.Mouse.preventDefault(ev);
setPActive(v => !v);
}}>
{React.string("Toggle Parent Active")}
</button>
<div>
{React.string("Parent")}
{pactive ? React.string("Active") : React.string("Inactive")}
</div>
<Children active />
</div>;
};
If I profile the above code with react dev tool, I can observe the following behaviors.
- When parent component updates, it updates all the children components even when the parent component update does not affect the prop being passed to the children. In the example above, clicking on
Toggle Parent Active
should only set the state forpactive
.active
does not change yet the child still rerender. - “Stateless” component (i.e.
Grandchildren
) still rerender everytime even when there is no props being pass.
Can someone explain why this is happening and what can I do to avoid unnecessary render.