DEV Community

Discussion on: Why You Should Be Writing React Custom Hooks

Collapse
 
ganeshshetty195 profile image
Ganesh Shetty

You have mentioned, you can't call a hook (like useEffect) in an ordinary helper function that is declared outside of a component

But we can call hook in any Plain JS function rite

Collapse
 
codescript profile image
Cobbygraves

No you can't call hooks in a plain JavaScript function either outside the component function or inside

Collapse
 
ganeshshetty195 profile image
Ganesh Shetty

import { useState, useEffect } from "react";
const CustomUtil = (url) => {
    const [data, setData] = useState(null);
    useEffect(() => {
        fetch(url)
            .then((res) => res.json())
            .then((data) => setData(data));
    }, [url]);
    return [data];
};

export default CustomUtil;

`this is a plain function with hooks in it
Enter fullscreen mode Exit fullscreen mode