microsoft / applicationinsights-react-js

Microsoft Application Insights React plugin
MIT License
35 stars 13 forks source link

Does useTrackEvent trigger re-render? #27

Closed VitaliyPotapov closed 10 months ago

VitaliyPotapov commented 1 year ago

As useTrackEvent actually returns setData from useState - does it mean it will trigger component re-render every time I send event?

Karlie-777 commented 1 year ago

@VitaliyPotapov it is returning the setData function, but not calling it setData(). So it will not directly re-rendered. And if you are using versions after React 16, calling setState with null also won't trigger an update.

VitaliyPotapov commented 1 year ago

Thanks Karlie! I'd like to clarify: every time I send event I actually call returned setData() -> state gets updated and from my understanding component will re-render. Is it correct?

I'm thinking why useTrackEvent is implemented as useState + useEffect, not just useCallback.

Karlie-777 commented 1 year ago

@VitaliyPotapov Thanks for clarification! I guess you are using useTrackEvent() like this example So return setData() directly for useTrackevent() could give you more controls on trackEvent data!

VitaliyPotapov commented 1 year ago

Yes I also wrap useTrackEvent in useCallback. But my question is about extra re-render that seems to occur even in your example. Please correct me if I'm wrong:

  1. user clicks on button, onClick handler calls setTestNumber(curTestNumber + 1)
  2. component state changed -> 1st re-render -> useEffect calls trackEvent(testNumber) that writes to state new testNumber
  3. component state changed again -> 2nd re-render (extra re-render!)
  4. process finished because no useEffect dependencies changed

My question is - could we avoid extra re-render by implementing useCustomEvent without writing to component state? For example like this:

export default function useCustomEvent<T>(
  reactPlugin: ReactPlugin,
  eventName: string,
  eventData: T,
): AIReactCustomEvent<T> {
  return useCallback(() => {
    reactPlugin.trackEvent({ name: eventName }, data);
  }, [reactPlugin, data, eventName]);
}
Karlie-777 commented 1 year ago

@VitaliyPotapov I thought you were referring to duplicated events are being triggered. 😊And you are correct! useCallBack() definitely optimizes performance by skipping re-rendering! However, downside of using useCallback hook is suggested here (correct me if I am wrong)

github-actions[bot] commented 11 months ago

This Issue will be closed in 30 days. Please remove the "Stale" label or comment to avoid closure with no action.