pmndrs / drei

🥉 useful helpers for react-three-fiber
https://drei.pmnd.rs/
MIT License
7.83k stars 642 forks source link

`useTexture(..., onLoad)` callback fires incorrectly #1968

Open jwueller opened 1 month ago

jwueller commented 1 month ago

Problem description:

The onLoad callback fires every render if the callback isn't memoized, because useEffect hook depends on the function instead of the mapped texture data. On the other hand, if the callback is memoized, it will only fire once and then never again, even if the data finishes loading later.

Relevant code:

const texture = useTexture(
    'some_texture.jpg',
    () => console.log('every render'),
);

Caused by this code in useTexture:

useLayoutEffect(() => {
  onLoad?.(mappedTextures)
}, [onLoad])

Suggested solution:

useLayoutEffect(() => {
  onLoad?.(mappedTextures)
}, [mappedTextures])

I will provide a PR with this change.