Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks check what state change caused re-render

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?

like image 957
ZenVentzi Avatar asked Oct 17 '22 05:10

ZenVentzi


1 Answers

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];
};
like image 134
Estus Flask Avatar answered Nov 09 '22 16:11

Estus Flask