How do you track the render count of `function components` in React Native?

Viewed 4275

Ideally I'd like to drop a little circle component in each component and see a render count on screen.

How do you track re-renders with hooks / function components?

1 Answers

OK, got back to this and figured out something that works for my purposes.

import React, { useRef } from 'react';
import { TextInput } from 'react-native';

const SHOW_RENDER_COUNTERS = true;

const useRenderCounter = () => {
  const renderCount = useRef(0);
  renderCount.current = renderCount.current + 1;

  if (__DEV__ && SHOW_RENDER_COUNTERS) {
    return (
      <TextInput
        style={{
          backgroundColor: 'hsl(0, 100%, 50%)',
          borderRadius: 6,
          color: 'hsl(0, 0%, 100%)',
          fontSize: 10,
          fontWeight: 'bold',
          height: 35,
          margin: 2,
          textAlign: 'center',
          width: 35,
        }}
        value={String(renderCount.current)}
      />
    );
  }
  return null;
};

export default useRenderCounter;

(Use SHOW_RENDER_COUNTERS to globally show/hide the counters.)

Then you inline it in the component you wish to track.

const Bubble = () => {
  const renderCounter = useRenderCounter();

  return (
    <>
      <BubbleCoomponentCode />
      {renderCounter}
    </>
  );
};

And end up with something like this.

Related