4

I have gallery that repositions components. I want it to reposition components when child components are changed: added, switched.

I was listening to children using useEffect hook:

useEffect(() => {
    items = [...layout.current.childNodes].filter(
      (el) => el.nodeType === 1 && +getComputedStyle(el).gridColumnEnd !== -1,
    );
    console.log('>>> Gallery: children changed!', children.props.items);
    setLayout();
  }, [children]);

As for parent I had a following layout:

<Gallery>
      <Cards items={pageGalleryItems} />
</Gallery>

Cards component displays some item info like price, name. I noticed that when I change settings to display different currency, I would expect cards to display different currency and nothing more, but gallery thinks that my children nodes changed and repositions all elements. It made me question whether it's fine to be listening to children components with useEffect? Or how to listen to child nodes being properly changed: replaced, added?

Alyona
  • 1,682
  • 2
  • 21
  • 44

1 Answers1

-1

useEffect is triggered on the 1st render as well as changes in states/props.

So if you are looking to detect a change in children components, try having a state that feeds children-content through props.

Once your useEffect is triggered, a new render is made and children receive their new content from the modified state.

I suggest you get familiarised with the notion of lifting-up states

Nour SIDAOUI
  • 164
  • 5