Skip to content

Commit b34103c

Browse files
authored
Update instance removal logic on component unmount (#153)
1 parent 6b53fc9 commit b34103c

File tree

1 file changed

+33
-23
lines changed

1 file changed

+33
-23
lines changed

src/index.tsx

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,63 @@
11
import diff from "microdiff";
22
import p5 from "p5";
3-
import React, { createRef, FC, memo, useState } from "react";
3+
import React, { createRef, FC, memo, MutableRefObject, useRef } from "react";
44
import { useIsomorphicEffect } from "rooks";
55

66
type Wrapper = HTMLDivElement;
7-
8-
export interface SketchProps {
7+
export type Sketch = (instance: P5CanvasInstance) => void;
8+
export type SketchProps = {
99
[key: string]: any;
10-
}
11-
12-
export interface Sketch {
13-
(instance: P5Instance): void;
14-
}
15-
16-
export interface P5WrapperProps extends SketchProps {
10+
};
11+
export type P5WrapperProps = SketchProps & {
1712
sketch: Sketch;
18-
}
19-
20-
export interface P5Instance extends p5 {
13+
};
14+
export type P5CanvasInstance = p5 & {
2115
updateWithProps?: (props: SketchProps) => void;
22-
}
16+
};
17+
18+
// @TODO: remove in next major version, keep for compatibility reasons for now.
19+
export type P5Instance = P5CanvasInstance;
2320

24-
function createCanvas(sketch: Sketch, wrapper: Wrapper): P5Instance {
21+
function createCanvasInstance(
22+
sketch: Sketch,
23+
wrapper: Wrapper
24+
): P5CanvasInstance {
2525
return new p5(sketch, wrapper);
2626
}
2727

28+
function removeCanvasInstance(
29+
canvasInstanceRef: MutableRefObject<P5CanvasInstance | undefined>
30+
) {
31+
canvasInstanceRef.current?.remove();
32+
canvasInstanceRef.current = undefined;
33+
}
34+
2835
const ReactP5WrapperComponent: FC<P5WrapperProps> = ({
2936
sketch,
3037
children,
3138
...props
3239
}) => {
3340
const wrapperRef = createRef<Wrapper>();
34-
const [instance, setInstance] = useState<P5Instance>();
41+
const canvasInstanceRef = useRef<P5CanvasInstance>();
3542

3643
useIsomorphicEffect(() => {
3744
if (wrapperRef.current === null) {
3845
return;
3946
}
4047

41-
instance?.remove();
42-
const canvas = createCanvas(sketch, wrapperRef.current);
43-
setInstance(canvas);
48+
removeCanvasInstance(canvasInstanceRef);
49+
canvasInstanceRef.current = createCanvasInstance(
50+
sketch,
51+
wrapperRef.current
52+
);
4453
}, [sketch]);
4554

46-
useIsomorphicEffect(() => {
47-
instance?.updateWithProps?.(props);
48-
}, [props, instance]);
55+
useIsomorphicEffect(
56+
() => canvasInstanceRef.current?.updateWithProps?.(props),
57+
[props]
58+
);
4959

50-
useIsomorphicEffect(() => () => instance?.remove(), []);
60+
useIsomorphicEffect(() => () => removeCanvasInstance(canvasInstanceRef), []);
5161

5262
return <div ref={wrapperRef}>{children}</div>;
5363
};

0 commit comments

Comments
 (0)