Search code examples
javascriptreactjsreact-hooksuse-effectuse-state

How to later use a method on a object that is stored in useState?


I have a custom hook something like this:

export const useSomeHook = () => {
    const [provider, setProvider] = useState(null);
        
    useEffect(() => {
        // init stuff using third party library
        setProvider(...);
    }, []);
    
    return [provider];
} 

In the application i use somewhere in read only mode, but the provider has methods that i want to use also which looks like this:

provider.once(txHash, (transaction) => {
    // Emitted when the transaction has been mined
})

The problem is due to the useState, it creates a read only object, so i cannot use the method of the provider. I cant just pass in data to initialize this function in the hook because txHash is something that changes with user interaction, and the provider is connected to websocket (which is initiated by the third party library during initialization.)


Solution

  • I guess it should work if you use a useRef instead of useState

    export const useSomeHook = () => {
        const providerRef = useRef(null);
            
        useEffect(() => {
            // init stuff using third party library
            providerRef.current = ...
        }, []);
        // you don't need to put it in an array since it's only one item
        return providerRef.current;
    }