React: [eslint-plugin-react-hooks]: Can't call hooks on component returned from function

Created on 11 May 2019  路  2Comments  路  Source: facebook/react

Wrapping a component in a function, returning the component.

tl;dr

export function Home() {
    return function() {
        const [ items, setItems ] = useState([])
        return <div>nothing</div>
    } 
}

const root = document.getElementById('root')
ReactDOM.render(React.createElement(Home()), root)

Results in the following error:

React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function

However this works:

export function Home() {
        const [ items, setItems ] = useState('')
        return <div>nothing</div>
}

const root = document.getElementById('root')
ReactDOM.render(React.createElement(Home), root)
ESLint Rules Question

Most helpful comment

It's not possible for the eslint plugin to detect that the function you've defined is a component, unless you provide some kind of hint. Giving it a name 'solves' this and silences the warning -

export function Home() {
    return function HomeComponent() {
        const [ items, setItems ] = useState([])
        return <div>nothing</div>
    } 
}

All 2 comments

It's not possible for the eslint plugin to detect that the function you've defined is a component, unless you provide some kind of hint. Giving it a name 'solves' this and silences the warning -

export function Home() {
    return function HomeComponent() {
        const [ items, setItems ] = useState([])
        return <div>nothing</div>
    } 
}

Line 13: React Hook "useReciepe" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks

Search for the keywords to learn more about each error.

App .js
useEffect(() => {
useReciepe();
}, []);
const useReciepe = async () => {
const response = await fetch(
https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}
);
const data = await response.json();
setRecipes(data.hits);
};

Am getting this error help me out

Was this page helpful?
0 / 5 - 0 ratings