Skip to content

Commit 552c9e9

Browse files
jamesrwebyevdyko
authored andcommitted
Update instance removal logic on component unmount
1 parent 6b53fc9 commit 552c9e9

File tree

1 file changed

+31
-23
lines changed

1 file changed

+31
-23
lines changed

src/index.tsx

+31-23
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,61 @@
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 } from "react";
4+
import { useRef } from "react";
45
import { useIsomorphicEffect } from "rooks";
56

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

24-
function createCanvas(sketch: Sketch, wrapper: Wrapper): P5Instance {
22+
function createCanvasInstance(
23+
sketch: Sketch,
24+
wrapper: Wrapper
25+
): P5CanvasInstance {
2526
return new p5(sketch, wrapper);
2627
}
2728

29+
function removeCanvasInstance(
30+
canvasInstanceRef: MutableRefObject<P5CanvasInstance | undefined>
31+
) {
32+
canvasInstanceRef.current?.remove();
33+
canvasInstanceRef.current = undefined;
34+
}
35+
2836
const ReactP5WrapperComponent: FC<P5WrapperProps> = ({
2937
sketch,
3038
children,
3139
...props
3240
}) => {
3341
const wrapperRef = createRef<Wrapper>();
34-
const [instance, setInstance] = useState<P5Instance>();
42+
const instanceRef = useRef<P5CanvasInstance>();
3543

3644
useIsomorphicEffect(() => {
3745
if (wrapperRef.current === null) {
3846
return;
3947
}
4048

41-
instance?.remove();
42-
const canvas = createCanvas(sketch, wrapperRef.current);
43-
setInstance(canvas);
49+
removeCanvasInstance(instanceRef);
50+
instanceRef.current = createCanvasInstance(sketch, wrapperRef.current);
4451
}, [sketch]);
4552

46-
useIsomorphicEffect(() => {
47-
instance?.updateWithProps?.(props);
48-
}, [props, instance]);
53+
useIsomorphicEffect(
54+
() => instanceRef.current?.updateWithProps?.(props),
55+
[props]
56+
);
4957

50-
useIsomorphicEffect(() => () => instance?.remove(), []);
58+
useIsomorphicEffect(() => () => removeCanvasInstance(instanceRef), []);
5159

5260
return <div ref={wrapperRef}>{children}</div>;
5361
};

0 commit comments

Comments
 (0)