-
Notifications
You must be signed in to change notification settings - Fork 51
Description
Hi there!
Thanks for a nifty little wrapper! 🙏🏼
I'm having some issues in my Next.js setup however, the P5 instance keeps running when I navigate between pages. I may very well just have missed something in my implementation for the below issue - but I couldn't figure out what 🤷🏼.
NB. I import using next/dynamic ReactP5Wrapper to avoid SSR:
const ReactP5Wrapper = dynamic(
() => {
return import("react-p5-wrapper")
.then((m) => m.ReactP5Wrapper)
.catch(console.error);
},
{ ssr: false }
);Expected Behavior
When a component including a <P5Wrapper> is unmounted, I would expect the P5 instance to be cleaned up and removed (with remove()).
Actual Behavior
The P5 instance continues to live and run even though the component is unmounted.
Steps to Reproduce the Problem
Here's a codesandbox demonstrating the issue: https://codesandbox.io/s/prod-architecture-tf8l0
- Navigate to "Page with ReactP5Wrapper", containing the P5 example.
- Navigate back the landing page again and notice components on page B are unmounted but the P5 instance is still running (the console.log from within the sketch's
draw()keeps running when using the browser's back button).
Workaround / suggested solution
I've worked around it by wrapping the wrapper (....🤪) and keeping tabs on the p5 instance with a ref, and removing it on unmount:
const SketchWrapper = ({ sketch }) => {
const p5InstancRef = useRef();
useEffect(() => {
return () => {
if (p5InstancRef.current) {
p5InstancRef.current.remove();
}
};
}, []);
return (
<ReactP5Wrapper
sketch={(p5) => {
p5InstancRef.current = p5;
sketch(p5);
}}
/>
);
};Package Version: 3.1.0