Skip to content

Instantly share code, notes, and snippets.

@dylangolow
Created September 2, 2022 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylangolow/a1938546d2dd5bcdb8e676866daa550f to your computer and use it in GitHub Desktop.
Save dylangolow/a1938546d2dd5bcdb8e676866daa550f to your computer and use it in GitHub Desktop.
Test code to check frequency of re-render based on state variable updates while using useEffect hook.
import { useEffect, useState } from "react";
export const ComponentX: React.FC = () => {
const [stateVar, setStateVar] = useState(undefined);
const [numberGeoRequests, setNumberGeoRequests] = useState(0);
const [lastRequestTime, setLastRequestTime] = useState(
new Date().getTime(),
);
useEffect(() => {
// ... logic
setNumberGeoRequests(numberGeoRequests + 1);
const requestTime = new Date().getTime();
setLastRequestTime(requestTime);
console.log({
numberGeoRequests,
time: requestTime,
timeISO: new Date(requestTime).toISOString(),
timeMsSinceLastRequest: lastRequestTime
? requestTime - new Date(lastRequestTime).getTime()
: 0,
});
setStateVar(true);
// further logic...
}, [setStateVar]);
};
export default ComponentX;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment