How to use a utility class instance in react different components and prevent reinitialization and only one instance is used on all components

Viewed 46

I have a class in a separate file and two or more different react components that need to use the class methods

One approach was I initially created an instance of the class outside the react components to prevent re rendering and having re-initialize the class

const utilityClass = new UtilityClass()
function ReactComponent() {
  const doSomething = () => {
    return utilityClass.doingSomething()
  }
}

but then for the second react component in a different file I will have to do the same thing right like below

const utilityClass = new UtilityClass()
function SecondReactComponent() {
  const doSomething = () => {
    return utilityClass.doingSomething()
  }
}

Even though it wont re-initialize on component re-render I am still creating an instance of the utility class multiple times across the different react components so I tried useMemo which also worked like below:

function SecondReactComponent() {
  const utilityClass = useMemo(() => new utilityClass(), []);
  const doSomething = () => {
    return utilityClass.doingSomething()
  }
}

And I am wondering which is the best approach because I also tried useCallback and for some reason that did not work and will appreciate if someone gave me more insights on the best practice to do this thanks

1 Answers

Just instantiate the class and export it at the top level of one of your modules. For example:

./First.jsx:

// class UtilityClass {/* ...*/}

export const utilityClass = new UtilityClass();

export function ReactComponent () {
  const doSomething = () => {
    return utilityClass.doingSomething();
  };
}

Then, in every other module where you want to use it (in other components, etc.), just import and use it:

./Second.jsx:

import {utilityClass} from './First';

export function SecondReactComponent () {
  const doSomething = () => {
    return utilityClass.doingSomething();
  };
}

Related