React hooks check what state change caused re-render
Asked Answered
A

1

6

Now with hooks, I've got the component's state split into more miniature states. This seemed better until I wanted to find out what state change caused a specific re-render.

How can one easily find out what state change caused a specific re-render?

Adne answered 16/3, 2019 at 10:20 Comment(6)
Do you refer to the componentWillUpdate (or componentDidUpdate) style checks where you have current and future (or previous) state?Verve
What is it that you are trying to accomplish? There might be some other way of going about it.Bricole
@Bricole for a moment I thought I'm chatting with Eckhart Tolle and became so damn present :D Anyway, I don't think I can explain it better, I want to know what state change caused a specific re-render. E.g. you have setVar1, setVar2, setVar3, all derived from useState, and I want to know which one of these caused the re-renderAdne
Which purpose do you want to know this for? Debugging? State management?Pageboy
@estus currently for debugging but there could be other use casesAdne
The big shift in thinking from class components to function components with hooks is that instead of checking what changed in e.g. componentDidUpdate, you use useEffect with the dependencies given in an array as second argument so that the effect runs automatically when the dependencies change. You could create a useEffect for each piece of state you have.Bricole
P
5

If state updates need to be tracked for state management like accessing previous state values, this should be handled explicitly with custom hooks that wrap useState.

As for debugging, React dev tools currently don't offer this functionality, although this information may be available through renderer undocumented API used in dev tools.

It's possible to add a breakpoint inside React dispatchAction function and walk call stack up to know which state setter was called:

debug useState

Or custom hook can be used instead of useState to keep track of state updates:

const useDebuggableState = initialState => {
  const [state, setState] = useState(initialState);

  useMemo(() => {
    'a line to add breakpoint';
  }, [state]);

  return [state, setState];
};
Pageboy answered 16/3, 2019 at 12:14 Comment(1)
This is amazing!!! Just putting a breakpoint in dispatchAction helped me see the function call triggering the infinite rerenders.Desensitize

© 2022 - 2024 — McMap. All rights reserved.