Endless loop on update and useEffect
deshiknaves opened this issue · 1 comments
deshiknaves commented
function customHook(initial = '') {
const [savedSearch, saveSearch] = useLocalStorageState('search', { search: initial })
const [search, setSearch] = useState(savedSearch.search)
useEffect(() => {
saveSearch({ search })
mockUpdateCallback(search)
}, [search, saveSearch])
return [search, setSearch]
}
Doing something like above completely breaks in an endless loop. This was not a problem in 4.x.x
. The saveSearch
function does not appear to be the same version. Removing the saveSearch
from the dependency will work, but that's not the right thing to do.
deshiknaves commented
it.only('returns the same update function on multiple renders', () => {
const mockUpdateCallback = jest.fn()
function useCustomHook(initial = '') {
const [savedSearch, saveSearch] = useLocalStorageState('search', { search: initial })
const [search, setSearch] = useState(savedSearch.search)
const count = useRef(0)
useEffect(() => {
if (count.current > 5) return
count.current += 1
saveSearch({ search })
mockUpdateCallback(search)
}, [search, saveSearch])
return [search, setSearch]
}
const { result } = renderHook(() =>
useCustomHook('test'),
)
expect(mockUpdateCallback.mock.calls).toEqual([['test']])
})
This test will show that this get's called 6 times instead of 1. This is because of the defaultValue
changing. I'll raise a PR soon to fix this.