Skip to content

P5 instances not remove()'d on component unmount? #142

@fredrikelmegren

Description

@fredrikelmegren

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

  1. Navigate to "Page with ReactP5Wrapper", containing the P5 example.
  2. 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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions