Skip to content

Instantly share code, notes, and snippets.

@carlesba
Last active January 6, 2022 16:58
Show Gist options
  • Save carlesba/66a4869976b84fd5ac2ba6ed84e1b883 to your computer and use it in GitHub Desktop.
Save carlesba/66a4869976b84fd5ac2ba6ed84e1b883 to your computer and use it in GitHub Desktop.
A hook to prevent useCallback in handlers
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];
}
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