Skip to content

Instantly share code, notes, and snippets.

@sorenlouv
Last active April 18, 2024 16:21
Show Gist options
  • Save sorenlouv/780ae8ca1e2cf59050b0695c901b5aa3 to your computer and use it in GitHub Desktop.
Save sorenlouv/780ae8ca1e2cf59050b0695c901b5aa3 to your computer and use it in GitHub Desktop.
Determine which props causes React components to re-render
import React, { Component } from 'react';
export default function withPropsChecker(WrappedComponent) {
return class PropsChecker extends Component {
componentWillReceiveProps(nextProps) {
Object.keys(nextProps)
.filter(key => {
return nextProps[key] !== this.props[key];
})
.map(key => {
console.log(
'changed property:',
key,
'from',
this.props[key],
'to',
nextProps[key]
);
});
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
// Usage
withPropsChecker(MyComponent)
@shunfan
Copy link

shunfan commented May 7, 2019

TypeScript version:

import * as React from 'react';

interface Props<P> {
  [key: string]: any;
}

export default function withPropsChecker<P>(WrappedComponent: React.ComponentType<P>): React.ComponentClass<Props<P>> {
  return class PropsChecker extends React.Component<Props<P>> {
    componentWillReceiveProps(nextProps: Props<P>) {
      Object.keys(nextProps)
        .filter(key => nextProps[key] !== this.props[key])
        .map((key) => {
          console.log(
            'changed property:',
            key,
            'from',
            this.props[key],
            'to',
            nextProps[key],
          );
        });
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}

@IamFonky
Copy link

IamFonky commented Oct 17, 2019

Here's a React typescript function component version

import * as React from 'react';

// TYPES
interface PropsCheckerProps<T> {
  children: (props: T) => React.ReactElement | null;
  childrenProps: T;
  compType?: ComparaisonTypes;
  verbose?: boolean;
}
interface Props {
  [key: string]: unknown;
}
type ComparaisonTypes = 'SIMPLE' | 'SHALLOW' | 'DEEP';

// COMPARAISON FUNCTIONS
function simpleCheck(a: unknown, b: unknown) {
  return a !== b;
}
function shallowCheck(a: unknown, b: unknown, verbose?: boolean) {
  if (typeof a !== typeof b) {
    verbose && console.log('Not the same type');
    return false;
  }
  if (typeof a !== 'object') {
    return simpleCheck(a, b);
  }
  const A = a as Props;
  const B = b as Props;
  const keys = Object.keys(A);
  if (!deepCheck(A, B, verbose)) {
    verbose && console.log('Objects keys changed');
    return false;
  }
  for (const k in keys) {
    if (simpleCheck(A[k], B[k])) {
      verbose && console.log(`Object differ at key : ${k}`);
      return false;
    }
  }
  return true;
}
function deepCheck(a: unknown, b: unknown, verbose?: boolean) {
  try {
    return JSON.stringify(a) !== JSON.stringify(b);
  } catch (e) {
    verbose && console.log(e);
    return false;
  }
}
function compFNSelection(compType: ComparaisonTypes) {
  switch (compType) {
    case 'SIMPLE':
      return (a: unknown, b: unknown, _verbose?: boolean) => simpleCheck(a, b);
    case 'SHALLOW':
      return (a: unknown, b: unknown, verbose?: boolean) =>
        shallowCheck(a, b, verbose);
    case 'DEEP':
      return (a: unknown, b: unknown, verbose?: boolean) =>
        deepCheck(a, b, verbose);
    default:
      console.log('Comparaison type unvailable. Test will always return false');
      return () => false;
  }
}

/**
 * This component wraps another one and logs which props changed
 * Warning, this component is not meant to be used in production mode as it's slowing the rendering and using extra memory
 * @param WrappedComponent The component to analyse
 * @param compType The possible comparaison type (Be carefull with "DEEP". It may get errors in case of circular references)
 */
export function ReactFnCompPropsChecker<T extends Props>(
  props: PropsCheckerProps<T>,
) {
  const { children, childrenProps, compType = 'SIMPLE', verbose } = props;
  const oldPropsRef = React.useRef<T>();
  React.useEffect(() => {
    const oldProps = oldPropsRef.current;
    if (oldProps === undefined) {
      console.log('First render : ');
      Object.keys(childrenProps).forEach(k =>
        console.log(`${k} : ${childrenProps[k]}`),
      );
    } else {
      const changedProps = Object.keys(childrenProps)
        .filter(k =>
          compFNSelection(compType)(oldProps[k], childrenProps[k], verbose),
        )
        .map(k => `${k} : [OLD] ${oldProps[k]}, [NEW] ${childrenProps[k]}`);
      if (changedProps.length > 0) {
        console.log('Changed props : ');
        changedProps.forEach(console.log);
      } else {
        console.log('No props changed');
      }
    }
    oldPropsRef.current = childrenProps;
  }, [childrenProps, compType, verbose]);
  return children(childrenProps);
}

Use it like that :

<ReactFnCompPropsChecker childrenProps={{prop1:...,prop2:...,...}}>
  {props=>(<TestedComponent{...props}/>)}
</ReactFnCompPropsChecker>

I hope it helps

@raffaele-abramini
Copy link

What about a forEach, instead of map? We are not really using the returned array

@IamFonky
Copy link

IamFonky commented Jan 21, 2020

You're right raffaele. I managed to change it in my codes recently. Sadly I'm not yet a js specialist and I still often misuse some basic methods.
I just edited the code now :)

@mozmorris
Copy link

mozmorris commented Apr 18, 2020

  1. The map was needed 🤦
  2. return JSON.stringify(a) === JSON.stringify(b); should be return JSON.stringify(a) !== JSON.stringify(b);
  3. a === b should be a !== b

@IamFonky
Copy link

IamFonky commented Apr 18, 2020

1. The `map` was needed facepalm

2. `return JSON.stringify(a) === JSON.stringify(b);` should be `return JSON.stringify(a) !== JSON.stringify(b);`

3. `a === b` should be `a !== b`

You're are totally right!
The map is needed as the loop have to return something : const changedProps = Object.keys(childrenProps)... and the comparison should me made on a non equality!

I edited the code to take into account your review.

@raffaele-abramini
Copy link

Sorry mate, I should have provided more details:

I meant in here as well as in the typescript version,

not in the React typescript function component version.

@IamFonky
Copy link

Hahaha, my bad too. I made de changes without really reviewing. Saturday work style xD

@mozmorris
Copy link

...forgot to say earlier, thank you for this - saved me some time creating something similar. Thank you :-)

@mozmorris
Copy link

If you wanted to take it a bit further instead of simply logging the props, there’s a useful package to diff objects which will output the difference. Very useful when nothing has really changed, but simply the ref.

@lrpinto
Copy link

lrpinto commented Apr 21, 2020

This is good. However, what do you think of logging changes on componentDidUpdate, instead of componentWillReceiveProps, therefore not delaying the rendering :)

@kulkarnipradnyas
Copy link

@IamFonky it is giving only initial props, how can i check prop in the case of react-select change?

@IamFonky
Copy link

@kulkarnipradnyas I don't really understand your question. What do you mean by react-select change? If you use a select component, the onChange function won't trigger any changes in his own props... can you provide an example of what you try to do please?

@kulkarnipradnyas
Copy link

kulkarnipradnyas commented Jul 19, 2020

@IamFonky I am trying it on story book and trying to check my react-select component, i wrote some consoles..it is rendering 4 time while selecting dropdown value.Thought to check due to which props its rerendering. but it is providing me props only at the time of loading only. On change event of that my react-select it is giving below.
<ReactFnCompPropsChecker
compType='DEEP'
childrenProps={{
variant: 'form-select',
optionList: options,
label: 'Name',
required: true,
loading: false,
onChange: (input: string) => console.log(input),
error: false,
errorMessage: '',
placeholder: '',
value: 'emailVerificationPending',
width: '300px'
}}
>
{() => (
<DropDown
variant={text('variant', 'form-select') as tSelectVariant}
optionList={object('optionList', options)}
label={text('label', 'Name')}
required={boolean('required', true)}
loading={boolean('loading', false)}
onChange={action('Value selected')}
error={boolean('error', false)}
errorMessage={text('errorMessage', '')}
placeholder={text('placeholder', '')}
value={text('value', 'emailVerificationPending')}
width={text('width', '300px')}
/>
)}

First render :
variant : form-select
optionList : [object Object],[object Object],[object Object]
label : Name
required : true
loading : false
onChange : function onChange(input) {
return console.log(input);
}
error : false
errorMessage :
placeholder :
value : emailVerificationPending
width : 300px

@IamFonky
Copy link

IamFonky commented Jul 19, 2020

You're not using the same props you gave to the checker comp in the DropDown. So you may be recreating props and making the DropDown rerender here.

You did this :

[...]
 >
{() => (
<DropDown
[...]

But you should do this :

[...]
 >
{(props) => (
<DropDown {...props}\>
[...]

As I wrote in my first comment, use it like that :

<ReactFnCompPropsChecker childrenProps={{prop1:...,prop2:...,...}}>
  {props=>(<TestedComponent{...props}/>)}
</ReactFnCompPropsChecker>

Use the variable given back to the children component in your DropDown in order to ensure you're looking at the same values.

I hope it helped you @kulkarnipradnyas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment