What is the best way to create a class instance variable only once in a React functional component?

Viewed 230

I have a class instance variable that I create using new operator. I want this to be created only once throughout the lifecycle of a React functional component. Should I create it outside the component or inside useEffect or use useMemo or some other way?

1 Answers

I think the best way to implement this would be to setup a context to store the var and then access/initialize it in the component.

Alternatively, you can also use a singleton via this package for example : react-singleton-hook . It's less "react standard" but singleton being a well known design pattern, it may be more readable and maintainable.

Related