Weird behavior when clicking on anchor link nav with background scene

Hi there,

This my first topic on this forum, I hope i didn’t make a mistake with duplicate/section of this question.

I just started using Three js and this library is very awesome !

I created a project with vite+react+typescript and i wanted to add a background scene animation (skybox that rotate) on all of the pages/section of my project, unfortunately I’m facing a weird behavior that i can’t understand that’s why I’m requesting the help of the community.

In fact, in my project I have an anchor link menu that scroll on different section when clicking on it. When the click has been done, the page scroll to the section but meanwhile the background scene becomes white and restart playing when the section is reached.
You can also reproduce this behavior just to scrolling between contents.

I created a codesandbox to illustrate this behavior here : youthful-bash-s98yrg

Is there a way to keep animation runing while interacting with the dom content ? Or am I doing something wrong ?

Hope this is clear, if not, do not hesitate to ask me more information.

thanks in advance.

i think this is because you execute side effects in the render function. there should be nothing in it, just hooks and the view. no “new Foo()” no loader.load(…), these are all effects, and they execute every time the component re-renders, so basically you are re-fetching everything from scratch on every prop change, this is most likely where the freeze-ups come from.

  • local fixed state belongs into const [foo] = useState(() => new Foo())
  • local dynamic state into const foo = useMemo(() => new Foo(arg), [arg])
  • side-effect belong into useEffect(() => loader.load(url), [loader, url])

but many of these things have been taken care of by fiber or its eco system. for instancing loading, use useLoader for that, or helpers you find in drei. for instance your three canvas code boils down to 5 lines. these helpers handle side effects properly, they won’t give you any issues.

import { Environment, OrbitControls } from '@react-three/drei'

<Canvas>
  <OrbitControls autoRotate autoRotateSpeed={0.5} enableZoom={false} />
  <Environment background files={[three, one, five, six, four, two]} />
</Canvas>

drei has lots of very useful helpers, you should definitively check it out: GitHub - pmndrs/drei: 🥉 useful helpers for react-three-fiber

1 Like

Thank you very much @drcmda that’s solve my problem.
Just two questions by curiosity :

  1. it seems that my new scene with drei is darker than the previous one with fiber, do you know why ?

  2. Three js is well know for its performance but do you know if its better to use a gif or video in background rather than a three js scene ? I can’t estimate this

Thank you again for your answer, it works pretty well know ^^