Junior — Senior
Preserving a class object between renders using useRef
livecode
Task condition
Let's conduct an experiment to see if the useRef hook preserves the same class instance after each re-render of the component and whether the value of the creationTime property changes. The constructor and each render output the corresponding data to the console.
import { useRef, useState } from "react";
class MyClass {
public creationTime;
constructor(value: number) {
this.creationTime = value;
console.log(value);
}
}
export default function MyComponent() {
const classInstanceRef = useRef(new MyClass(new Date().getTime()));
const [, triggerRender] = useState<Symbol>(Symbol());
console.log(classInstanceRef.current.creationTime);
return (
<div>
<h1>Hello world</h1>
<button onClick={() => triggerRender(Symbol())}>
update state
</button>
</div>
);
}