welldone-software / why-did-you-render

why-did-you-render by Welldone Software monkey patches React to notify you about potentially avoidable re-renders. (Works with React Native as well.)
https://www.npmjs.com/package/@welldone-software/why-did-you-render
MIT License
11.11k stars 196 forks source link

Missing `ownerDataMap` in `notifier` #281

Open zeorin opened 10 months ago

zeorin commented 10 months ago

When providing a getAdditionalOwnerData function in the options, there is no ownerDataMap provided to the notifier.

Based on a reading of the source, it also seems to me that passing ownerDataMap to the notifier is probably not what was meant, but that it should probably be passed the additionalOwnerData instead, given that ownerDataMap is accessible at whyDidYouRender.wdyrStore.ownerDataMap anyway. additionalOwnerData is also not passed to notifier.

At runtime, the additionalOwnerData is actually added to the values in wdyrStore.ownerDataMap, but nothing is done with them.

Additionally, if one tries to get the additionalOwnerData oneself inside the notifier by retrieving it from the whyDidYouRender.wdyrStore.ownerDataMap using either the prevProps or the nextProps, this doesn't work, as the props that are used for the keys are the element's props, and not the owner's props. It is the owner's props that are passed to the notifier.

I was able to work around this by creating my own mapping between owner props and element props, so that I could lookup the element props to use as the key to the ownerDataMap:

import React from 'react';
import whyDidYouRender from '@welldone-software/why-did-you-render';

const { defaultNotifier, wdyrStore } = whyDidYouRender;

const elementOwnerPropsMap = new WeakMap();

whyDidYouRender(React, {
  getAdditionalOwnerData: (element) => {
    const owner = wdyrStore.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner.current; // is this the same as `element._owner`?
    elementOwnerPropsMap.set(owner.pendingProps, element.props);
    return { owner };
  },
  notifier: (updateInfo) => {
    const { additionalOwnerData } = wdyrStore.ownerDataMap.get(
      elementOwnerPropsMap.get(updateInfo.prevProps) // `updateInfo.nextProps` never matches anything
    ) ?? {};

    // do stuff with `additionalOwnerData`…

    defaultNotifier(updateInfo);
  },
});