简体   繁体   中英

Detect when any part of component tree has changed in React

I have two components, Parent and Child :

function Child() {
  const [counter, setCounter] = React.useState(0);

  React.useEffect(() => {
    const interval = setInterval(() => setCounter(counter + 1), 1000);
    return () => clearInterval(interval);  
  }, [counter, setCounter]);

  return <div>{counter}</div>;
}

function Parent() {
  return <Child />;
}

Child is just a simple timer that increments/renders a counter.

From Parent ( ie my root component), how can I know when any part of the component tree has changed? For example, when Child updates its state and re-renders?

Passing a callback to Child is not a solution, because in a real app, I would have hundreds of children, and I need to know any time any part of the component tree changes.

I tried using useEffect / componentDidUpdate in Parent , but that doesn't get called when a child managing its own state re-renders. Is there a way to achieve what I want?

It looks like a Redux use case. You can achieve this easily on redux.

I think what you should try doing is have each component be able to know if the current render cycle will cause a DOM change, based on whatever props or state have changed. Then call a function provided through Context (a provider in the component that wants to know about the changes, a subscriber in each child) to let the parent know a change has happened. You can call this function in a useEffect so that it happens after the DOM changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM