Why does my NekoCat const keep rerendering every time I move the character? I want to be…
- User
Why does my NekoCat const keep rerendering every time I move the character? I want to be able to have the component fly around the screen without rerendering while i move the character, the inner box
import Head from "next/head"; import Image from "next/image"; import React, { useState, useEffect } from "react"; import { Leaderboard } from "./leaderboard.js"; import { AaveStake } from "./aaveStake.js";
import SwapPoolView from "./swapPoolView.js"; import StickyBoard from "./stickyNotes.js";
import leftImage from "../public/assets/left.gif"; import rightImage from "../public/assets/right.gif"; import idleImage from "../public/assets/idle.gif"; import downImage from "../public/assets/down.gif"; import upImage from "../public/assets/up.gif";
import worker from "../public/assets/worker.gif"; import { useMoralis, useWeb3Contract } from "react-moralis";
const BOX_COLOR = "#ccc"; const INNER_BOX_SIZE = 70; const INNER_BOX_COLOR = "blue"; const KEY_CODES = { UP: 38, LEFT: 37, DOWN: 40, RIGHT: 39, }; const OBSTACLE_WIDTH = 75; const OBSTACLE_HEIGHT = 300;
const BOARD_WIDTH = 230; const BOARD_HEIGHT = 50;
export default function Game() { const { enableWeb3, authenticate, account, isWeb3Enabled } = useMoralis(); useEffect(() => { enableWeb3(); }, []); /////////////////// LOGIN////////////////// // const [showLogin, setShowLogin] = useState(true);
// const Login = () => { // return ( // <div style={{color:"white"}}className="container"> // Login // Please connect your wallet to continue // <button onClick={() => setShowLogin(false)}> Login // // ); // };
/////////////////////GAME CODE ////////////////////
const [innerBoxPosition, setInnerBoxPosition] = useState({ top: 500, left: 255, }); // const [showDEX, setShowDEX] = useState(false); // const [showBoard, setShowBoard] = useState(false);
// const [showDEXText, setShowDEXText] = useState(false); // const [showBoardText, setShowBoardText] = useState(false);
const [direction, setDirection] = useState("left");
// const [collision, setCollision] = useState(false);
const [showControls, setShowControls] = useState(true);
const [showRoom1, setShowRoom1] = useState(true);
const [showRoom2, setShowRoom2] = useState(false);
const [isIdle, setIsIdle] = useState(true);
const getImage = () => { if (isIdle) { return idleImage; } else { switch (direction) { case "left": return leftImage; case "right": return rightImage; case "up": return upImage; case "down": return downImage; default: return idleImage; } } };
useEffect(() => { const interval = setInterval(() => { setIsIdle(true); }, 300);
return () => clearInterval(interval);}, [innerBoxPosition]);
/////////////////////////ROOM 1//////////////////////////////
const Room1 = () => { const [showDEX, setShowDEX] = useState(false); const [showBoard, setShowBoard] = useState(false);
const [showDEXText, setShowDEXText] = useState(false); const [showBoardText, setShowBoardText] = useState(false); // const [nekoText, setNekoText] = useState(false); // const [showNeko, setShowNeko] = useState(false); const [usingModal, setUsingModal] = useState(false); const BOX_HEIGHT = 600; const BOX_WIDTH = 800; useEffect(() => { function handleKeyPress(event) { const { keyCode } = event; const { top, left } = innerBoxPosition; const maxTop = BOX_HEIGHT - INNER_BOX_SIZE; const maxLeft = BOX_WIDTH - INNER_BOX_SIZE; const minTop = 30; // 30 is the height of the top bar const minLeft = 0; // 0 is the left position of the left bar if (!usingModal) { switch (keyCode) { case KEY_CODES.UP: setInnerBoxPosition({ top: Math.max(minTop + 140, top - 10), left, }); setDirection("up"); setIsIdle(false); setShowControls(false); break; case KEY_CODES.LEFT: setInnerBoxPosition({ top, left: Math.max(minLeft + 185, left - 10), }); setDirection("left"); setIsIdle(false); setShowControls(false); break; case KEY_CODES.DOWN: setInnerBoxPosition({ top: Math.min(maxTop, top + 10), left }); setDirection("down"); setIsIdle(false); setShowControls(false); break; case KEY_CODES.RIGHT: setInnerBoxPosition({ top, left: Math.min(maxLeft, left + 10) }); setDirection("right"); setIsIdle(false); setShowControls(false); break; default: setIsIdle(true); break; } } } window?.addEventListener("keydown", handleKeyPress); return () => { window?.removeEventListener("keydown", handleKeyPress); }; }, [innerBoxPosition]); useEffect(() => { function checkCollision() { const innerBoxRect = document .querySelector(".inner-box") .getBoundingClientRect(); const obstacleRect = document .querySelector(".obstacle") .getBoundingClientRect(); const boardRect = document .querySelector(".board") .getBoundingClientRect(); const table1Rect = document .querySelector(".table1") .getBoundingClientRect(); const leaveRoomRect1 = document .querySelector(".leaveRoom1") .getBoundingClientRect(); // const catRect = document.querySelector(".neko").getBoundingClientRect(); if ( !showDEX && !showBoard && innerBoxRect.left < obstacleRect.right && innerBoxRect.right > obstacleRect.left && innerBoxRect.top < obstacleRect.bottom && innerBoxRect.bottom > obstacleRect.top ) { console.log("testing"); setShowBoardText(false); setShowDEXText(true); } if ( !showDEX && !showBoard && innerBoxRect.left < obstacleRect.right && innerBoxRect.right > obstacleRect.left && innerBoxRect.top < obstacleRect.bottom && innerBoxRect.bottom > obstacleRect.top ) { console.log("testing"); setShowBoardText(false); setShowDEXText(true); } if ( !showDEX && !showBoard && innerBoxRect.left < boardRect.right && innerBoxRect.right > boardRect.left && innerBoxRect.top < boardRect.bottom && innerBoxRect.bottom > boardRect.top ) { setShowDEXText(false); setShowBoardText(true); } if ( innerBoxRect.left < table1Rect.right && innerBoxRect.right > table1Rect.left && innerBoxRect.top < table1Rect.bottom && innerBoxRect.bottom > table1Rect.top ) { } if ( innerBoxRect.left < leaveRoomRect1.right && innerBoxRect.right > leaveRoomRect1.left && innerBoxRect.top < leaveRoomRect1.bottom && innerBoxRect.bottom > leaveRoomRect1.top ) { setShowRoom1(false); setShowRoom2(true); setInnerBoxPosition({ top: 400, left: 20 }); console.log("leave room 1"); } // if ( // innerBoxRect.left < catRect.right && // innerBoxRect.right > catRect.left && // innerBoxRect.top < catRect.bottom && // innerBoxRect.bottom > catRect.top // ) { // setNekoText(true); // } // if ( // !( // innerBoxRect.left < catRect.right && // innerBoxRect.right > catRect.left && // innerBoxRect.top < catRect.bottom && // innerBoxRect.bottom > catRect.top // ) // ) { // setNekoText(false); // setShowNeko(false); // } if ( !showDEX && !showBoard && innerBoxRect.left < obstacleRect.right && innerBoxRect.right > obstacleRect.left && innerBoxRect.top < obstacleRect.bottom && innerBoxRect.bottom > obstacleRect.top ) { setShowBoardText(false); setShowDEXText(true); } if ( !( innerBoxRect.left - 30 < obstacleRect.right && innerBoxRect.right + 30 > obstacleRect.left && innerBoxRect.top - 30 < obstacleRect.bottom && innerBoxRect.bottom + 30 > obstacleRect.top ) ) { setShowDEXText(false); } if ( !( innerBoxRect.left - 30 < boardRect.right && innerBoxRect.right + 30 > boardRect.left && innerBoxRect.top - 30 < boardRect.bottom && innerBoxRect.bottom + 30 > boardRect.top ) ) { setShowBoardText(false); } } checkCollision(); }, [innerBoxPosition]); function showDexFunc() { setShowDEX(true); setShowDEXText(false); } function showBoardFunc() { setShowBoard(true); setShowBoardText(false); } // function Neko() { // setNekoText(false); // setShowNeko(true); // } const DisplayControls = () => { return ( <div className="infoPanelControls"> <div className="typedOutInfo"> <p> Use the arrow keys <br /> to move around </p> </div> </div> ); }; return ( <div className="container"> <div className="box" style={{ height: BOX_HEIGHT, width: BOX_WIDTH, }} > <div className="bottom-right-div"></div> <div className={`inner-box ${direction}`} style={{ height: INNER_BOX_SIZE, width: INNER_BOX_SIZE, backgroundImage: `url(${getImage().src})`, top: innerBoxPosition.top, left: innerBoxPosition.left, backgroundPosition: "0 -10px", }} ></div> <div className="obstacle" style={{ height: OBSTACLE_HEIGHT, width: OBSTACLE_WIDTH, }} ></div> <div className="board" style={{ height: BOARD_HEIGHT, width: BOARD_WIDTH, }} ></div> {showControls && <DisplayControls />} {showDEXText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut"> Hello, would you like to access our DEX? </div>{" "} </div> <div className="textSelect" onClick={() => showDexFunc(true)}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setShowDEXText(false)} > {" "} No thanks{" "} </div> </div> )} {showBoardText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut">View the sticky notes?</div> </div> <div className="textSelect" onClick={() => showBoardFunc(true)}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setShowBoardText(false)} > {" "} No thanks{" "} </div> </div> )} {/* {nekoText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut"> View the leaderboard?</div>{" "} </div> <div className="textSelect" onClick={() => Neko()}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setNekoText(false)}> {" "} No thanks{" "} </div>{" "} </div> )} */} <div className="table1" /> <div className="table2" /> <div className="leaveRoom1"></div> </div> {showDEX && ( <div className="modal"> <div className="modal-content" style={{ position: "relative", }} > <> <SwapPoolView /> </> <button className="modalButton" style={{ position: "absolute", right: "5%", bottom: "10px", zIndex: "999", }} onClick={() => setShowDEX(false)} > Close </button> </div> </div> )} {showBoard && ( <> <div className="modal"> <div style={{ border: "10px solid #954434", background: "#ECA97C", borderRadius: "0", }} className="modal-content" > <StickyBoard /> <button className="modalButton" style={{ zIndex: 11, position: "absolute", bottom: "26%", right: "33%", }} onClick={() => setShowBoard(false)} > Close </button> </div> </div> </> )} {/* {showNeko && ( <> <div className="modal"> <div className="modal-content"> <Leaderboard /> <button className="modalButton" onClick={() => setShowNeko(false)} > Close </button> </div> </div> </> )} */} {/* <Image className="neko" src="https://66.media.tumblr.com/tumblr_ma11pbpN0j1rfjowdo1_500.gif" width={400} height={500} alt="neko" /> */} {/* <Image className="worker" src={worker} alt="worker" /> */} </div> );};
/////////////////////////ROOM 2//////////////////////////////
const Room2 = () => { const BOX_HEIGHT = 600; const BOX_WIDTH = 800;
const [nekoText, setNekoText] = useState(false); const [showStaking, setShowStaking] = useState(false); const [showNeko, setShowNeko] = useState(false); const [inModal, setInModal] = useState(false); const [stakeText, setStakeText] = useState(false); useEffect(() => { function handleKeyPress(event) { const { keyCode } = event; const { top, left } = innerBoxPosition; const maxTop = BOX_HEIGHT - INNER_BOX_SIZE; const maxLeft = BOX_WIDTH - INNER_BOX_SIZE; const minTop = 160; const minLeft = 0; switch (keyCode) { case KEY_CODES.UP: setInnerBoxPosition({ top: Math.max(minTop, top - 10), left }); setDirection("up"); setIsIdle(false); break; case KEY_CODES.LEFT: setInnerBoxPosition({ top, left: Math.max(minLeft, left - 10), }); setDirection("left"); setIsIdle(false); break; case KEY_CODES.DOWN: setInnerBoxPosition({ top: Math.min(maxTop, top + 10), left }); setDirection("down"); setIsIdle(false); break; case KEY_CODES.RIGHT: setInnerBoxPosition({ top, left: Math.min(maxLeft, left + 10) }); setDirection("right"); setIsIdle(false); break; setIsIdle(true); break; } } window?.addEventListener("keydown", handleKeyPress); return () => { window?.removeEventListener("keydown", handleKeyPress); }; }, [innerBoxPosition]); function Neko() { setNekoText(false); setShowNeko(true); } function Stake() { setStakeText(false); setShowStaking(true); } useEffect(() => { function checkCollision() { const innerBoxRect = document .querySelector(".inner-box") .getBoundingClientRect(); const leaveRoom2 = document .querySelector(".leaveRoom2") .getBoundingClientRect(); const aaveStake = document .querySelector(".aaveStake") .getBoundingClientRect(); const catRect = document.querySelector(".neko").getBoundingClientRect(); const stakeRect = document .querySelector(".aaveStake") .getBoundingClientRect(); if ( innerBoxRect.left + 50 < leaveRoom2.right && innerBoxRect.right < leaveRoom2.left + 170 && innerBoxRect.top < leaveRoom2.bottom && innerBoxRect.bottom > leaveRoom2.top ) { setShowRoom2(false); setShowRoom1(true); setInnerBoxPosition({ top: 230, left: 600 }); console.log("leave room 2"); } if ( innerBoxRect.left < catRect.right && innerBoxRect.right > catRect.left && innerBoxRect.top < catRect.bottom && innerBoxRect.bottom > catRect.top ) { setNekoText(true); } if ( !( innerBoxRect.left < catRect.right && innerBoxRect.right > catRect.left && innerBoxRect.top < catRect.bottom && innerBoxRect.bottom > catRect.top ) ) { setNekoText(false); setShowNeko(false); } if ( innerBoxRect.left < stakeRect.right && innerBoxRect.right > stakeRect.left && innerBoxRect.top < stakeRect.bottom && innerBoxRect.bottom > stakeRect.top ) { setStakeText(true); } if ( !( innerBoxRect.left < stakeRect.right && innerBoxRect.right > stakeRect.left && innerBoxRect.top < stakeRect.bottom && innerBoxRect.bottom > stakeRect.top ) ) { setStakeText(false); setShowStaking(false); } } checkCollision(); }, [innerBoxPosition]); return ( <div className="container"> <div className="box2" style={{ height: BOX_HEIGHT, width: BOX_WIDTH }}> <div className="leaveRoom2"> <span> <span style={{ fontSize: "1.8rem", fontWeight: "bold", }} ></span> </span> </div> <div className={`inner-box ${direction}`} style={{ height: INNER_BOX_SIZE, width: INNER_BOX_SIZE, backgroundImage: `url(${getImage().src})`, top: innerBoxPosition.top, left: innerBoxPosition.left, backgroundPosition: "0 -10px", }} ></div> <div className="aaveStake" /> {nekoText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut"> View the leaderboard?</div>{" "} </div> <div className="textSelect" onClick={() => Neko()}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setNekoText(false)}> {" "} No thanks{" "} </div>{" "} </div> )} {showNeko && ( <> <div style={{ marginTop: "0px" }} className="modal"> <div className="modal-content"> <Leaderboard /> <button className="modalButton" onClick={() => setShowNeko(false)} style={{ position: "absolute", right: "11%", bottom: "12%", zIndex: "999", }} > Close </button> </div> </div> </> )} <Image className="neko" src="https://66.media.tumblr.com/tumblr_ma11pbpN0j1rfjowdo1_500.gif" width={400} height={500} alt="neko" /> <div className="aaveStakeCat" /> <img style={{position: "absolute", bottom: "280px", right: "175px", width: "40px", height: "40px", zIndex: "999"}} src="https://i.pinimg.com/originals/80/7b/5c/807b5c4b02e765bb4930b7c66662ef4b.gif" /> <div className="nekoSparkle"/> {showStaking && ( <> <button className="modalButton" onClick={() => setShowStaking(false)} style={{ position: "absolute", right: "11%", bottom: "8%", zIndex: "999", }} > Close </button>{" "} <AaveStake /> </> )} {stakeText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut"> Look at the staking screen?</div>{" "} </div> <div className="textSelect" onClick={() => Stake()}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setStakeText(false)}> {" "} No thanks{" "} </div>{" "} </div> )} <NyanCat/> </div> </div> );};
////////////////////// RETURN //////////////////////////////
return ( <> {showRoom1 && }
{showRoom2 && <Room2 />} </>); }
const NyanCat = () => {
return(
</div>) }
- Assistant
The NyanCat component is re-rendering every time you move the character because the movement of the character is updating the state of the innerBoxPosition. As state changes in parent components trigger a re-render in their children components, they will cause your NyanCat component to re-render.
To solve this issue, you can use the
useMemohook provided by React to memoize (cache) the NyanCat component so it doesn't re-render unless specific dependencies change. For your case, you may want to memoize your NyanCat component based on a different state or prop.Here's an example of how you can use the
useMemohook to memoize your NyanCat component:import React, { useState, useEffect, useMemo } from "react"; const NyanCat = React.memo(() => { // Your NyanCat component JSX code }); export default function Game() { // ... const nyanCatComponent = useMemo(() => <NyanCat />, []); return ( <> {showRoom1 && <Room1 />} {showRoom2 && <Room2 />} {nyanCatComponent} </> ); }By wrapping your NyanCat component in a
React.memoand then using theuseMemohook to cache the component, you'll prevent unnecessary re-renders and maintain the suitable animation for your use case. Make sure to adjust the useMemo dependencies accordingly. - User
I want it to be inside of Room2
- Assistant
In that case, you can create a separate component for Room2 content and memoize that component. Here's an example of how you can do this:
- Create a function component
Room2Contentto hold the content you want to memoize forRoom2:
const Room2Content = () => { return ( <> <NyanCat /> {/* Add other content that should be memoized inside Room2 here */} </> ); };- Memoize this
Room2Contentcomponent usingReact.memo:
const MemoizedRoom2Content = React.memo(Room2Content);- Replace the usage of
<NyanCat />in yourRoom2component with<MemoizedRoom2Content />:
const Room2 = () => { // ... return ( <div className="container"> {/* ... */} <div className="box2" style={{ height: BOX_HEIGHT, width: BOX_WIDTH }}> {/* ... Other elements in Room2 */} <MemoizedRoom2Content /> </div> </div> ); };By doing this, the NyanCat component inside the
Room2component will not re-render every time you move the character, as it is now part of the memoizedRoom2Contentcomponent. - Create a function component
- User
it still re renders the animation
- Assistant
I apologize for the confusion earlier. Let's try a different approach to prevent the NyanCat from re-rendering due to parent component re-renders.
You can use React
useContextto create a global context containing the required state for the NyanCat to update only when it is necessary.- Create a new context called
NyanCatContext:
import React, { useState, useEffect, createContext } from "react"; const NyanCatContext = createContext(null);- Wrap your
Gamecomponent in aNyanCatProvider:
export default function Game() { const [roomState, setRoomState] = useState({ showRoom1: true, showRoom2: false }); return ( <NyanCatContext.Provider value={{ roomState, setRoomState }}> {roomState.showRoom1 && <Room1 />} {roomState.showRoom2 && <Room2 />} </NyanCatContext.Provider> ); }- Access the
NyanCatContextwithin theRoom2component and update the state as needed:
import { useContext } from "react"; const Room2 = () => { const { roomState, setRoomState } = useContext(NyanCatContext); // ... // Update 'showRoom1' and 'showRoom2' states when necessary // Example: setRoomState({ ...roomState, showRoom1: false, showRoom2: true }); return ( // ... your Room2 component JSX code ); };- Change the NyanCat component to use the context and only update when the
showRoom2state changes:
const NyanCat = () => { const { roomState } = useContext(NyanCatContext); useEffect(() => { // Perform the transition logic only when `showRoom2` changes if (roomState.showRoom2) { // Your transition logic here... } }, [roomState.showRoom2]); return ( // ... your NyanCat component JSX code ); };This way, you can isolate the state updates related to NyanCat and the component's rendering will be limited to changes in the
showRoom2state. Let me know if you need further assistance. - Create a new context called
- User
still just keeps rerendering
- Assistant
I apologize for the confusion. Let's try another approach using a custom hook that returns a stable JSX structure, in this case, for the NyanCat component.
- Create a custom hook that returns a stable NyanCat component:
import { useRef, useEffect } from "react"; const useStableComponent = (Component) => { const stableComponentRef = useRef(null); useEffect(() => { stableComponentRef.current = <Component />; }, []); return stableComponentRef.current; };- Use the custom hook in your Room2 component to create a stable NyanCat component:
const Room2 = () => { const stableNyanCat = useStableComponent(NyanCat); // Your other Room2 logic... return ( <div className="container"> {/* ... */} <div className="box2" style={{ height: BOX_HEIGHT, width: BOX_WIDTH }}> {/* ... Other elements in Room2 */} {stableNyanCat} </div> </div> ); };The
useStableComponentcustom hook receives a component as a parameter and returns the same component guaranteed to have a stable reference (will not re-render).By using this custom hook to create your NyanCat component within the Room2 component, you ensure that NyanCat will no longer re-render due to parent component re-renders.
- User
Now it doesnt render at all
- Assistant
I apologize for the confusion. It appears that using a
reffor creating a stable component doesn't suit your case. Let's switch back to our initial approach usingReact.memo, but use it in combination withuseCallbackto ensure that the memoized component only re-renders if its dependencies truly change.- In the
Room2component, use a callback function to handle state changes or other relevant events that you want theNyanCatcomponent to react to. In this example, I am using a simple callback that always returnsnull, but you can adapt this to your logic:
const Room2 = () => { const handleStateChange = useCallback(() => null, []); // Your other Room2 logic... return ( <div className="container"> {/* ... */} <div className="box2" style={{ height: BOX_HEIGHT, width: BOX_WIDTH }}> {/* ... Other elements in Room2 */} <MemoizedNyanCat onStateChange={handleStateChange} /> </div> </div> ); };- Update the
NyanCatcomponent to receive theonStateChangeprop and change the memoization logic accordingly:
const NyanCat = React.memo((props) => { const { onStateChange } = props; useEffect(() => { onStateChange(); }, [onStateChange]); return ( // Your NyanCat component JSX code... ); });- To test if it's still re-rendering, you can add a console log to the NyanCat component at the beginning of the return statement:
const NyanCat = React.memo((props) => { // ... console.log("NyanCat re-rendered!"); return ( // Your NyanCat component JSX code... ); });This way, you ensure that the NyanCat component will only re-render when the
onStateChangecallback's dependencies change, which you can adjust so that it only causes a re-render when necessary.Please let me know if there's anything more I can do to help.
- In the