Home > Back-end >  How to run useEffect() when children change size in React?
How to run useEffect() when children change size in React?

Time:07-17

I want to update the layout of a component when its children change size. I have a parent component DetailView that composes dynamic child components, which may change size as the user manipulates them. When this happens, I want the parent component to refresh the layout.

EDIT: I am concerned with the size of the children rendered on screen, not the number of children.

Each time a component in the layout changes size I need to run the updateLayout() function. I do now want to pass the updateLayout() function to each child as a prop, which I view as undesirable coupling between the child components and the layout system.

The snippet below should illustrate what I want, but it doesn't fire when the children change size.

useEffect(() => {
    console.log("Children changed");
    updateLayout();
  }, Children.toArray(children));

CodePudding user response:

children is an array so all you have to do is add the children.length as a dependency array to useEffect

As soon as the chidren length changes then updateLayout function will get called.

useEffect(() => {
    console.log("Children changed");
    updateLayout();
}, [children.length]);

CodePudding user response:

useEffect allows you to perform side effects from a function component. When useEffect is called, React knows to render your side effect only after changes are made to the DOM. And changing children's size is just changing the style (CSS) And CSS does not change the DOM .

  • Related