1

The most common use of React Refs is to store a DOM element. However, the React documentation suggests that refs can be used to store any immutable value, so I was wondering if anyone has been able to implement an actual instance of a class and assigned it to a ref. E.g.:

// Example class
class MyBlueCar {
  constructor(options) {

  }
  ...
}

// React component
import { MyBlueCar } from "./mybluecar.js";

function StartCar() {
  const startEngineRef = useRef();

  useEffect(() => {
    const myBlueCar = new MyBlueCar();
    startEngineRef.startEngine = myBlueCar
  }, []);
}

However I get a startEngineRef is not extensible error.

1 Answer 1

5

The ref, startEngineRef, is read only. startEngineRef.current is mutable.

startEngineRef.current.startEngine = myBlueCar

In your case, you may consider

const startEngine = React.useMemo(() => new MyBlueCar(), [])

if you just want to have a single instance for the whole life cycle of the component.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.