Updating colors dynamically using React Hooks?

I’m trying to update the scene background dynamically using a npm package that’s called ‘react-colorful’.

So far it works great, debugging the color picker with console.log() returns desired colors but Three.js doesn’t seem to update it when I change it using the hooks from React.

So my goal is to dynamically update the scene.background color when using the color picker. The color picker has no issues, returns everything dynamically when I debugged it.

Here is what I tried so far, if you need more information, feel free to ask.

My code is heavily based on this CodePen

const ThreePromoKitAnim = () => {
  const [currBackground, setBackground] = useState('#ff0000')
  const mount = useRef()
  
  useEffect(() => {
    // initialization of scene, camera
    mount.current.appendChild(renderer.domElement)
  }, [])

  // value = returned color value from the color picker
  const handleBackgroundChange = (value) => {
    setBackground(value)
    scene.background = new THREE.Color(currBackground)
  }

  return (
    <>
      <HexColorPicker
        color={currBackground}
        onChange={handleBackgroundChange}
     />
     <div className='threejs' ref={mount} />
    </>
  )
}

Also, I’ve noticed that when React auto updates the page (when saving code) and I set another value of the background color using the color picker it does work but not dynamically.

Am I missing something? Why doesn’t the background change dynamically? How can I use hooks to dynamically change the background? Is there another workaround to dynamically change the color?

Many thanks in advance.

/cc

Yeah, I posted it in StackOverflow for more help… I’m really desperate as I have a deadline.

It’s totally fine to post in multiple places but you should crosslink them to prevent people from answering questions that are already answered.

You could also try asking on one of the r3f message boards.

1 Like