Last active
January 6, 2022 16:58
-
-
Save carlesba/66a4869976b84fd5ac2ba6ed84e1b883 to your computer and use it in GitHub Desktop.
A hook to prevent useCallback in handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import EventEmitter from "events"; | |
import { useCallback, useEffect, useRef } from "react"; | |
export default function useListener(listener = () => {}) { | |
const emitter = useRef(new EventEmitter()); | |
useEffect(() => { | |
const currentEmitter = emitter.current; | |
currentEmitter.on("event", listener); | |
return () => { | |
currentEmitter.off("event", listener); | |
}; | |
}, [listener]); | |
const dispatch = useCallback((...payload) => { | |
emitter.current.emit("event", ...payload); | |
}, []); | |
return [dispatch, emitter]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import useListener from './useListener' | |
function Table({ onChangeSelection }) { | |
const [value] = useTable(config) | |
const [dispatch] = useListener(onChangeSelection) | |
const { selected } = value.state | |
useEffect(()=> { | |
dispatch(selected) | |
// dispatch won't change when onChangeSelection changes | |
}, [selected, dispatch]) | |
// ... | |
} | |
function Page() { | |
const [selection, setSelection] = useState({}) | |
const handleSelection = useCallback(, []) | |
return ( | |
<div> | |
<OtherComponent selection={selection} /> | |
{/* we can use inline functions for handlers with ease now */} | |
<Table onChangeSelection={(value) => setSelection(value)} /> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment