Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom hook that recives dependencies?

I'm making a custom hook that have a toogle when some state change.

You should be able to pass any state in an array.

import { useState, useEffect } from 'react'

const useFlatListUpdate = (dependencies = []) => {
    const [toggle, setToggle] = useState(false)

    useEffect(() => {
        setToggle(t => !t)
    }, [...dependencies])

    return toggle
}

export default useFlatListUpdate

And it should be used as

const toggleFlatList = useFlatListUpdate([search, selectedField /*, anything */])

But it gives me the following warning

React Hook useEffect has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies.eslint(react-hooks/exhaustive-deps)

I also have another situation where it doesn't work

const useFlatListUpdate = (dependencies = []) => {
    const [toggle, setToggle] = useState(false)

    useEffect(() => {
        setToggle(t => !t)
    }, dependencies)

    return toggle
}

This gives me the warning

React Hook useEffect was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies.eslint(react-hooks/exhaustive-deps)

How can I make this work without the warning and without disabling eslint?

like image 483
Vencovsky Avatar asked Oct 02 '19 23:10

Vencovsky


People also ask

Can I use useEffect in custom hook?

What is the React UseEffect? The useEffect hook has superpowers that enable us to design our custom hooks. When a change occurs, it allows us to perform side effects in functional components. It allows data retrieval, DOM modification, and function execution each time a component renders.

When would you create a custom hook?

Why and When To Use Custom Hooks. The main reason to write a custom hook is for code reusability. For example, instead of writing the same code across multiple components that use the same common stateful logic (say a “setState” or localStorage logic), you can put that code inside a custom hook and reuse it.


1 Answers

Use of dependency list is very peculiar in this case.
I do not see other way except ignoring or silencing the warning.

To silence the warning, we do not have to disable eslint completely.
You can disable this specific rule for this specific line:

const useFlatListUpdate = (dependencies = []) => {
    const [toggle, setToggle] = useState(false)

    /* eslint-disable react-hooks/exhaustive-deps */
    useEffect(() => {
        setToggle(t => !t)
    }, [...dependencies])

    return toggle
}
like image 188
ckedar Avatar answered Sep 17 '22 13:09

ckedar