5

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?

ZenVentzi
  • 3,945
  • 3
  • 33
  • 48
  • Do you refer to the `componentWillUpdate` (or `componentDidUpdate`) style checks where you have current and future (or previous) state? – Meir Mar 16 '19 at 10:56
  • 2
    What is it that you are trying to accomplish? There might be some other way of going about it. – Tholle Mar 16 '19 at 10:58
  • 1
    @Tholle 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-render – ZenVentzi Mar 16 '19 at 11:22
  • Which purpose do you want to know this for? Debugging? State management? – Estus Flask Mar 16 '19 at 11:24
  • @estus currently for debugging but there could be other use cases – ZenVentzi Mar 16 '19 at 11:27
  • 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`](https://reactjs.org/docs/hooks-reference.html#timing-of-effects) 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. – Tholle Mar 16 '19 at 11:30

1 Answers1

3

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];
};
Estus Flask
  • 206,104
  • 70
  • 425
  • 565