mousetrap
mousetrap copied to clipboard
using mousetrap with react does my solution lead to memory leaks
I am using mousetrap in a react app and I have a generic component that assigns the handlers and removes them when the component is unmounted.
I'm going to write this as if you don't know react and hopefully you might :).
In react components have lifecycle events, one of these is componentDidMount
and I am passing in props to a Shortcuts
component and assigning them first of all in componentDidMount
:
export class Shortcuts extends React.PureComponent<ShortcutsProps, ShortcutsState> {
resolveShorcuts = (): Shortcut[] => {
const { createShortcuts, children } = this.props;
const component = React.Children.only(children) as any;
const ref = component.ref;
if (!ref) {
return createShortcuts(component.props);
}
const instance = (component as any).ref.current; // TOOD: cast to component
return createShortcuts(component.props, instance);
};
buildShortcuts = () => {
this.clearShortcuts();
const shortcuts = this.resolveShorcuts();
shortcuts.forEach((shortcut: Shortcut) => {
mousetrap.bind(shortcut.keySequence, shortcut.action);
});
this.setState({ shortcuts });
};
clearShortcuts = () => {
this.state.shortcuts.forEach(shortcut => mousetrap.unbind(shortcut.keySequence));
};
componentDidMount() {
this.buildShortcuts();
}
}
I am using the static bind
method and not using the constructor that would assign these event handlers to a dom element.
I am also recreating the shortcuts when the components props update in componentWillUpdate
I do this to create new handlers from the new props.
I have a clearShortcuts
method above that calls the static unbind
method of mousetrap
.
Does it behave as I expect or am I leaving myself open to memory leads?