Next.js Discord

Discord Forum

Why is the class constructor called again each render for a useRef?

Unanswered
Raymond posted this in #help-forum
Open in Discord
In my example code, I store the class Test whose constructor will set this.x = 1 and print to the console. When I rerender the page by pressing the render <button />, the constructor is called but this.x is not set to 1. Why is the constructor called again and why doesn't this.x return to 1?

"use client"

import React from "react";

export default function About(): React.JSX.Element {
    const [render, setRender] = React.useState<boolean>(true);
    const test = React.useRef<Test>(new Test);

    return <div>
        <button onClick={() => setRender(!render)}>render</button>
        <br /><br />
        <button onClick={() => test.current.add()}>add</button>
        <br /><br />
        <span>test.x = {test.current.x}</span>
    </div>
}


class Test {
    public x = 1;

    constructor() {
        console.log("Test initialized");
    }

    public add(): void {
        this.x++;
    }
}

0 Replies