-
Notifications
You must be signed in to change notification settings - Fork 54
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Example useEffect cleanup function? #573
Labels
triage me
I really want to be triaged.
type: question
Request for information or clarification. Not an issue.
Comments
|
This example is poorly written. The component creates a new instance of the google.maps.Map object on every render of the component. Google charges for every instance created. function MyMapComponent({
center,
zoom,
}: {
center: google.maps.LatLngLiteral;
zoom: number;
}) {
const ref = useRef();
useEffect(() => {
new window.google.maps.Map(ref.current, {
center,
zoom,
});
});
return <div ref={ref} id="map" />;
} Here is an improved version that only creates one instance of the google.maps.Map object: function MyMapComponent({
center,
zoom,
}: {
center: google.maps.LatLngLiteral;
zoom: number;
}) {
const ref = useRef();
const [map, setMap] = useState();
// Note the explicit empty array for dependencies here.
// This ensures that this effect will only run ONCE after the first render.
useEffect(() => {
// MapOptions here aren't strictly necessary here, but may reduce initialization
const map = new window.google.maps.Map(ref.current, {
center,
zoom,
});
setMap(map);
}, []);
useEffect(() => {
if (!map) return;
map.setZoom(zoom);
}, [map, zoom]);
useEffect(() => {
if (!map) return;
map.setCenter(center);
}, [map, center]);
return <div ref={ref} id="map" />;
} |
@deAtog thanks! Would you be able to quickly put that into the README and create a PR for it? |
I updated the example in #854 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Labels
triage me
I really want to be triaged.
type: question
Request for information or clarification. Not an issue.
The map is initialized via useEffect, but there is no cleanup function in the example code. Am I missing something?
The text was updated successfully, but these errors were encountered: