Evan Trimboli
Evan Trimboli

Reputation: 30082

useRef readonly value only at initialization

Moving to functional React components, useRef seems to be the way mirror class level variables. Consider:

class Component extends React.Component<Props> {
    private readonly foo: Something<Props>

    constructor(props: Props) {
      super(props)
      this.foo = new Something<Props>(props)
    }
}

In this case, the value of foo can't be reassigned.

const Component : React.FunctionComponent<Props> = (props: Props) => {
    const foo = useRef(new Something<Props>(props));
    return null;
};

In this case, foo.current is mutable, since useRef returns a MutableRefObject. Also it's going to initialize each time, which I don't want. Is there something built in to have these be immutable?

Upvotes: 2

Views: 3649

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51866

The Hooks FAQ contains a section on How to create expensive objects lazily. You can achieve your desired effect using the callback signature of useState():

const Component : React.FunctionComponent<Props> = (props: Props) => {
    const [foo] = React.useState(() => new Something<Props>(props) as const);
    return null;
};

Upvotes: 2

Related Questions