How to instantiate, store, and modify class variables in react-native?

I have class A

export class A {
    constructor(data){...}
    ...
}

And a component that imports A but shouldn’t instantiate it immediately.

...
import { A } from './A'

export const Acomponent = () => {
    var aInstance;

    const apiObject = apiCall(); // call some api
    useEffect(() => {
        if(apiObject.status === "success"){
            aInstance = new A(apiObject.data);
            ... // aInstance is still undefined here
        }
    }, [apiObject]);
}

Is a var the best way to store the class instance in this case? I don’t think a state would be an option because class functions would directly change the state without using the setState function.

Answer

You probably want useRef here.

import { A } from './A'

export const Acomponent = () => {
    const aRef = useRef()

    useEffect(() => {
        const apiObject = apiCall(); // call some api
        if(apiObject.status === "success"){
            aRef.current = new A(apiObject.data);
        }
    }, [apiObject]);


    return <>{aRef.current.whatever}</>
}

Just know that any changes to aRef will not re-render. If that’s a problem, then this is the wrong solution.


Or you could store the A construction params in state and build a new one every render. Or better memoize it so you only build a new one when it would create a different result:

const [aParams, setAParams] = useState({})

const aInstance = useMemo(() => new A(aParams), [aParams])

useEffect(() => {
  if(apiObject.status === "success") {
    setAParams(apiObject.data)
  }
}, [])

Or you could store the instance in state, but you have to treat the class as immutable. That means that if any value in that instance should change, you need to create a new instance and save it in state. Most classes can’t easily be made to work this way, so it’s probably not a great idea.