gracekrcx / weekly-notes

4 stars 0 forks source link

lodash debounce in React functional component #140

Open gracekrcx opened 1 year ago

gracekrcx commented 1 year ago

lodash debounce in React functional component not working Lodash debounce not working in React 看起來應該是因為 react functional component render 產生的 instance 不一樣 will be a new function for every render. You can use the useCallback hook to make sure that the same function is being persisted between renders and it will work as expected.

gracekrcx commented 1 year ago
 // initial render register addEventListener once
    useEffect(() => {
        window.addEventListener('scroll', onScroll)
        return () => window.removeEventListener('scroll', onScroll)
    }, [])

    const onScroll = _.throttle(() => {
        setValue(value)
    }, 100)