简体   繁体   中英

Return function from inside custom hook

I have the below custom hook;

export default function useFetch(url) {
    const [response, setResponse] = useState();
    useEffect(() => {
        const fetchresponse = async () => {
            // code to fetch response from api
        }
        fetchresponse();
    }, [url]);

    return [response];
}

While the above works fine from the start of my functional component, I want to make this reusable and invoke them from other places in my main component (eg button click) ie hit api on button click. Thus, I want to return an executable function, which can be invoked on say button click.

How can I do that and considering I have a useEffect here inside my custom hook?

Just define the function outside the useEffect hook.

Then it will be in scope to return.

function useFetch(url) {
    const [response, setResponse] = useState();

    const fetchresponse = async () => {
        // code to fetch response from api
    }

    useEffect(() => {
        fetchresponse();
    }, [url]);

    return [response, fetchresponse];
}

Optionally wrap the function in useCallback so it doesn't get redefined with each render.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM