The following component is being rendered at the top of a single page next js application. Instead of the cleanup function, how do i initially mount the component and only hide it when i navigate to a different section using next navigation which uses pageProps instead of full page reload. Logic Flow: initial globe is mounted on the index.jsx, when a user navigates to a different page, do not unmount the globe: import React, { useEffect, useRef } from 'react';
import {
WebGLRenderer,
Scene,
AmbientLight,
DirectionalLight,
Color,
Fog,
PerspectiveCamera,
PointLight
} from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { createGlowMesh } from 'three-glow-mesh';
import ThreeGlobe from "three-globe";
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
let mouseX = 0;
let mouseY = 0;
let timeoutId;
let renderer, camera, scene, controls;
let Globe;
let frameId;
If you want to maintain the globe component even when the user navigates to different sections of your Next.js application, the most straightforward approach would be to conditionally render the based on the route being accessed. Given that you're utilizing , one can assume that you are passing certain props to your pages to determine their content.
User
Assistant
User
Assistant
User
that does not add the globe to the div with classname globe-container
Assistant
// Event listeners
function onWindowResize() {
camera.aspect = windowWidth / windowHeight;
camera.updateProjectionMatrix();
windowHalfX = windowWidth;
windowHalfY = windowHeight;
renderer.setSize(windowWidth, windowHeight);
}
function onMouseMove(event) {
mouseX = event.clientX - windowHalfX;
mouseY = event.clientY - windowHalfY;
// console.log("x: " + mouseX + " y: " + mouseY);
}
// Animation
function animate() {
camera.lookAt(scene.position);
controls.update();
renderer.render(scene, camera);
frameId = requestAnimationFrame(animate);
}
useEffect(() => {
// Initialize core ThreeJS elements
function init() {
// Initialize renderer
renderer = new WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(globeWidth, globeHeight);
renderer.setClearColor(0x000000, 0);
containerRef.current.appendChild(renderer.domElement);
// Initialize scene, light
scene = new Scene();
scene.add(new AmbientLight(0xbbbbbb, 0.4));
// Initialize camera, light
camera = new PerspectiveCamera();
camera.aspect = globeWidth / globeHeight;
camera.updateProjectionMatrix();
var dLight = new DirectionalLight(0xffffff, 0.8);
dLight.position.set(-800, 2000, 400);
camera.add(dLight);
var dLight1 = new DirectionalLight(0x7982f6, 1);
dLight1.position.set(-200, 500, 200);
camera.add(dLight1);
var dLight2 = new PointLight(0x8566cc, 0.5);
dLight2.position.set(-200, 500, 200);
camera.add(dLight2);
camera.position.z = 400;
camera.position.x = 0;
camera.position.y = 0;
scene.add(camera);
// Additional effects
scene.fog = new Fog(0x535ef3, 400, 2000);
// Helpers
// const axesHelper = new THREE.AxesHelper(800);
// scene.add(axesHelper);
// var helper = new THREE.DirectionalLightHelper(dLight);
// scene.add(helper);
// var helperCamera = new THREE.CameraHelper(dLight.shadow.camera);
// scene.add(helperCamera);
// Initialize controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dynamicDampingFactor = 0.01;
controls.enablePan = false;
controls.minDistance = Math.min(globeWidth, globeHeight) / 2;
controls.maxDistance = Math.min(globeWidth, globeHeight) / 2;
controls.rotateSpeed = 0.8;
controls.zoomSpeed = 1;
controls.autoRotate = false;
controls.minPolarAngle = Math.PI / 3.5;
controls.maxPolarAngle = Math.PI - Math.PI / 3;
}
// Initialize the Globe
function initGlobe() {
// Initialize the Globe
Globe = new ThreeGlobe({
waitForGlobeReady: true,
animateIn: true,
})
.hexPolygonsData(countries.features)
.hexPolygonResolution(3)
.hexPolygonMargin(0.7)
.showAtmosphere(true)
.atmosphereColor("#ffffff")
.atmosphereAltitude(0.1)
.hexPolygonColor((e) => {
if (
["KEN", "CHN", "FRA", "ZAF", "JPN", "USA", "AUS", "CAN"].includes(
e.properties.ISO_A3
)
) {
return "rgba(255,255,255, 1)";
} else return "rgba(255,255,255, 0.5)";
});
// NOTE Arc animations are followed after the globe enters the scene
timeoutId = setTimeout(() => {
Globe.arcsData(travelHistory.flights)
.arcColor((e) => {
return e.status ? "#9cff00" : "#ff2e97";
})
.arcAltitude((e) => {
return e.arcAlt;
})
.arcStroke((e) => {
return e.status ? 0.5 : 0.3;
})
.arcDashLength(0.9)
.arcDashGap(4)
.arcDashAnimateTime(1000)
.arcsTransitionDuration(1000)
.arcDashInitialGap((e) => e.order * 1)
.labelsData(airportHistory.airports)
.labelColor(() => "#ffffff")
.labelDotOrientation((e) => {
return e.text === "NGA" ? "top" : "right";
})
.labelDotRadius(0.35)
.labelSize((e) => e.size)
.labelText("city")
.labelResolution(6)
.labelAltitude(0.01)
.pointsData(airportHistory.airports)
.pointColor(() => "#ffffff")
.pointsMerge(true)
.pointAltitude(0.07)
.pointRadius(0.10);
}, 1000);
Globe.rotateX(-Math.PI * (1 / 50));
Globe.rotateY(-Math.PI * (1 / 9));
Globe.rotateZ(-Math.PI / 60);
const globeMaterial = Globe.globeMaterial();
globeMaterial.color = new Color(0x3a228a);
globeMaterial.emissive = new Color(0x220038);
globeMaterial.emissiveIntensity = 0.1;
globeMaterial.shininess = 0.7;
// NOTE Cool stuff
// globeMaterial.wireframe = true;
scene.add(Globe);
}
init();
initGlobe();
onWindowResize();
animate();
window.addEventListener('resize', onWindowResize, false);
renderer.domElement.addEventListener('mousemove', onMouseMove);
console.log("Initializing globe animation");
return () => {
clearTimeout(timeoutId);
console.log({timeoutId})
window.removeEventListener('resize', onWindowResize);
renderer.domElement.removeEventListener('mousemove', onMouseMove);
cancelAnimationFrame(frameId);
if (containerRef.current) {
// Perform more thorough clean-up here
// Dispose of the scene's children
while (scene.children.length > 0) {
const object = scene.children[0];
if (object.dispose) {
object.dispose();
}
scene.remove(object);
}
// Dispose of the renderer and any associated resources
renderer.dispose();
// Dispose of any controls, if necessary
if (controls && controls instanceof OrbitControls && controls.dispose) {
controls.dispose();
}
if (renderer.domElement.parentNode === containerRef.current) {
// Remove the renderer DOM element
containerRef.current.removeChild(renderer.domElement);
}
}
};
}, [uniqueValue]);
return <div ref={containerRef} />;
};
export default GlobeComponent;
GlobeComponent
pageProps
Here's a conceptual approach:
Move Global State Up: Place the globe in a component that will not unmount when you change routes. Typically, this would be in a layout component or the custom _app.js file.
Conditional Rendering: Use the route information (accessible using the useRouter hook from next/router) to decide whether to show or hide the globe instead of mounting and unmounting it.
Below is an example of how to adjust your _app.js to always mount the GlobeComponent and only render it conditionally:
jsx
// pages/_app.js or your layout component
import { useRouter } from 'next/router';
import GlobeComponent from '../components/GlobeComponent';
function MyApp({ Component, pageProps }) {
const router = useRouter();
const showGlobe = router.pathname === '/'; // adjust condition as required
return (
<div>
{showGlobe && <GlobeComponent {...yourGlobeProps} />}
<Component {...pageProps} />
</div>
);
}
export default MyApp;
In the above example, yourGlobeProps would be whatever props you need to pass to GlobeComponent. The showGlobe variable is determined by the router.pathname: if it’s '/', it assumes you’re on the index page and should display the globe. Adjust the condition as needed based on your app's routing.
Since the _app.js component does not unmount when navigating between pages, the globe will remain mounted, and only its visibility is toggled. One thing to keep in mind is that you may want to adjust the z-index or positioning of the GlobeComponent to ensure it does not interfere with the content of other pages.
In addition, you might want to handle resizing or other window events globally, not just when the globe component is shown, to ensure it functions properly when it’s made visible again.
Remember to consider performance implications: maintaining a complex 3D graphics component in memory and potentially still executing its animation loop can be resource-intensive for the user’s device, even if not visible. You may want to pause or reduce the intensity of animation updates when the component is not visible.
how do i modify my code based on your suggestions above: GlobeComponent.jsx: import React, { useEffect, useRef } from 'react';
import {
WebGLRenderer,
Scene,
AmbientLight,
DirectionalLight,
Color,
Fog,
PerspectiveCamera,
PointLight
} from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { createGlowMesh } from 'three-glow-mesh';
import ThreeGlobe from "three-globe";
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
let mouseX = 0;
let mouseY = 0;
let timeoutId;
let renderer, camera, scene, controls;
let Globe;
let frameId;
Based on the provided code for GlobeComponent.jsx and _app.jsx, I'll guide you through integrating the conditional rendering as discussed before.
First, let's modify the _app.jsx to render GlobeComponent conditionally. We'll use useRouter from next/router at the top-level (_app.jsx) to check the current path and show the globe only on the homepage:
jsx
// _app.jsx
import { useRouter } from 'next/router';
import GlobeComponent from '../components/GlobeComponent'; // ensure this path is correct
import Layout from '../components/Layout';
import { AnimatePresence, motion } from 'framer-motion';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
const router = useRouter();
// Show GlobeComponent only when on the homepage (assuming this is your homepage route)
const showGlobe = router.pathname === '/';
return (
<Layout>
{showGlobe && <GlobeComponent />} {/* This will render the Globe on the homepage */}
<AnimatePresence mode="wait">
<motion.div key={router.route} className="h-full">
<Component {...pageProps} />
</motion.div>
</AnimatePresence>
</Layout>
);
}
export default MyApp;
Next, ensure your GlobeComponent is optimized to not perform unnecessary operations when it's not visible. To do this, the useEffect hook in GlobeComponent could be modified to listen for changes in visibility. Since we don't have such a prop right now, we'll keep it as it is, assuming the globe should always be initialized once on the first load.
Since you're going to show/hide the globe component without re-initializing it, you might want to think about the animation loop animate. You could introduce a way to pause and resume this loop based on the visibility to save resources. However, this would require sending a prop from _app.jsx to GlobeComponent, indicating if the globe should animate or not.
Also, whenever you're cleaning up in a useEffect return function, make sure you're not doing excess work that might not be required if the component will be shown again.
To summarize, the existing GlobeComponent code is already set up to initialize once and not tied to a specific uniqueValue with the removal of the dependency array in useEffect being empty. The _app.jsx has been modified to conditionally render the GlobeComponent only on the homepage defined by /.
Please remember to test thoroughly to ensure everything is working as expected, especially with Three.js, which can involve nuanced behavior, especially around memory management and rendering performance.
How would i then modify my index page to show the globeComponent from the _app.jsx in the div with class globe-container: import { motion } from "framer-motion";
import dynamic from 'next/dynamic';
import { useState, useEffect, useRef } from "react";
import Bulb from "../components/Bulb";
import ProjectsBtn from "../components/ProjectsBtn";
import TrackVisibility from 'react-on-screen';
import { fadeIn } from "../variants";
{/* subtitle */}
<motion.p
variants={fadeIn("down", 0.3)}
initial="hidden"
animate="show"
exit="hidden"
className="max-w-sm xl:max-w-xl mx-auto xl:mx-0 mb-10 xl:mb-16"
>
With a keen eye for design and a passion for code, I bring visions to life with precision and polish. Let's collaborate to create a stunning online presence that showcases your unique brand and leaves a lasting impression. Elevate your digital game with a developer who is committed to quality and innovation. {uniqueValue}
</motion.p>
{/* btn */}
<div className="flex justify-center xl:hidden relative">
<ProjectsBtn />
</div>
<motion.div
variants={fadeIn("down", 0.4)}
initial="hidden"
animate="show"
exit="hidden"
className="hidden xl:flex"
>
<ProjectsBtn />
</motion.div>
</div>
</div>
{/* image */}
<div className="w-[100%] xl:w-[50%] md:w-[100%] h-full pt-10 xl:mr-10 absolute xl:right-0 bottom-0">
{/* bg img */}
<div
role="img"
className="bg-none xl:bg-right xl:bg-no-repeat w-full h-full bg-cover bg-center relative"
aria-hidden
>
<motion.div
variants={fadeIn("up", 0.5)}
initial="hidden"
animate="show"
exit="hidden"
transition={{ duration: 1, ease: "easeInOut" }}
className="w-full h-full max-w-[100%] max-h-[100%] absolute"
>
<div className="globe-container">
<GlobeComponent
globeWidth={600}
globeHeight={600}
windowWidth={1000}
windowHeight={1000}
uniqueValue={uniqueValue}
ref={containerRef}
/>
</div>
</motion.div>
</div>
</div>
<Bulb />
</div>
);
};
export default Home;
Given that you want to show the GlobeComponent on the index page, you can use a conditional rendering approach within the _app.jsx. Better yet, you can still keep it in the _app.jsx for two reasons:
The _app.jsx wraps around all your pages, so it's a central place to control the visibility of UI elements like your globe, which need to be on multiple pages.
The GlobeComponent should not be unmounted and remounted as the user navigates between pages.
However, if you simply want to place the GlobeComponent within a specific layout component on the index page, you can use context or props to control where it renders, but keep in mind this involves more complex state management. Let's keep the logic simple and control the visibility centrally for now.
Here's the recommended approach to control the GlobeComponent from _app.jsx and show it inside the div with the globe-container class.
First, in your _app.jsx, set a state variable to track the current page and pass it down to the Layout:
jsx
// _app.jsx
import { useState } from 'react';
import { useRouter } from 'next/router';
import GlobeComponent from '../components/GlobeComponent';
import Layout from '../components/Layout';
import { AnimatePresence, motion } from 'framer-motion';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
const router = useRouter();
const [currentPage, setCurrentPage] = useState(router.route);
// Update the current page when the route changes
router.events.on('routeChangeComplete', (url) => setCurrentPage(url));
// Clean up the event listener
router.events.off('routeChangeComplete', (url) => setCurrentPage(url));
// Show GlobeComponent only when on the homepage
const showGlobe = currentPage === '/';
return (
<Layout>
<AnimatePresence mode="wait">
<motion.div key={router.route}>
{showGlobe && <GlobeComponent {...pageProps.globeProps} />}
<Component {...pageProps} />
</motion.div>
</AnimatePresence>
</Layout>
);
}
export default MyApp;
In your Home component, you don't need to dynamically import GlobeComponent. You also don't need to pass the ref to GlobeComponent since it's not using forwardRef() to forward its ref. So the Home component would look like this (and I've removed the GlobeComponent import):
jsx
// Home.jsx
import { motion } from "framer-motion";
import { useState, useEffect } from "react";
import Bulb from "../components/Bulb";
import ProjectsBtn from "../components/ProjectsBtn";
import TrackVisibility from 'react-on-screen';
import { fadeIn } from "../variants";
const Home = ({ uniqueValue }) => {
// ... no changes to your custom typing effect code...
return (
<div className="bg-primary/30 h-full overflow-x-auto">
{/* ...other code... */}
{/* Remove GlobeComponent since it's used in _app.jsx now */}
{/* ...other code... */}
<Bulb />
</div>
);
};
export default Home;
In essence, GlobeComponent has been moved up the hierarchy to _app.jsx and is now controlled there. Your Home component no longer needs to deal with it. The element is inserted into the layout when the homepage is displayed.
By managing the globe on the page level, you can ensure it stays mounted and doesn't reinitialize as users navigate your site, provided they don't fully refresh the page. However, keep an eye on potential performance issues, especially if the globe is resource-intensive.
I apologize for the misunderstanding earlier. If you want to have the GlobeComponent inside a specific div with class globe-container on your index page, you can directly include GlobeComponent within that div in your Home component.
This is how you would do it:
First, import the GlobeComponent in your Home component.
Then, place it directly inside the div with the class globe-container.
Finally, remove the conditional rendering of the GlobeComponent from _app.jsx because it is now included directly within the Home component.
Here's the updated Home component that includes GlobeComponent within the div.globe-container:
jsx
// Home.jsx
import { motion } from "framer-motion";
import { useState, useEffect } from "react";
import Bulb from "../components/Bulb";
import ProjectsBtn from "../components/ProjectsBtn";
import TrackVisibility from 'react-on-screen';
import { fadeIn } from "../variants";
import GlobeComponent from "../components/GlobeComponent"; // Ensure correct path
const Home = ({ uniqueValue }) => {
// ... your custom typing effect code ...
// ... other code ...
return (
<div className="bg-primary/30 h-full overflow-x-auto">
{/* ...other code... */}
{/* text */}
{/* ... */}
{/* Globe Container */}
<div className="globe-container">
<GlobeComponent
globeWidth={600}
globeHeight={600}
windowWidth={window.innerWidth} // Make it responsive to current window size
windowHeight={window.innerHeight}
/>
</div>
{/* ...other code... */}
<Bulb />
</div>
);
};
export default Home;
Note: It's important to ensure that the window dimensions are appropriately used to maintain responsiveness. You can leverage the useState and useEffect hooks to update the dimensions when the window is resized. You should also consider checking if SSR is getting in the way of window references and use a dynamic import with { ssr: false } if necessary.
Here is an example of handling window resize within the Home component for responsive dimensions:
jsx
// Inside Home.jsx
// State for window dimensions
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
// Handle window resize
useEffect(() => {
function handleResize() {
setDimensions({ width: window.innerWidth, height: window.innerHeight });
}
window.addEventListener('resize', handleResize);
handleResize(); // Call once immediately
return () => window.removeEventListener('resize', handleResize);
}, []);
// Then, pass the dimensions to your GlobeComponent
<GlobeComponent
globeWidth={600} // or use dimensions.width for full width
globeHeight={600} // or use dimensions.height for full height
windowWidth={dimensions.width}
windowHeight={dimensions.height}
/>
With these updates, your GlobeComponent will render inside the div with class globe-container specifically on your Home component, and it won't rely on global state or _app.jsx.