Skip to content

Instantly share code, notes, and snippets.

@fabien0102
Created August 31, 2018 14:21
Show Gist options
  • Save fabien0102/a3524e097b3c83e90460d138b59e666c to your computer and use it in GitHub Desktop.
Save fabien0102/a3524e097b3c83e90460d138b59e666c to your computer and use it in GitHub Desktop.
Debounce component render
import { DebounceSettings } from "lodash";
import lodashDebounce from "lodash/debounce";
import isBoolean from "lodash/isBoolean";
import isEmpty from "lodash/isEmpty";
import React from "react";
export const isNotFilterValue = (value: any) => {
return !isBoolean(value) && isEmpty(value);
};
export function debounce<TProps>(
Component: React.ComponentType<TProps>,
wait?: number,
options?: DebounceSettings
) {
return class Debounce extends React.Component<TProps, TProps> {
public state = this.props;
public shouldRender = false;
public updateState = lodashDebounce(
props => {
this.shouldRender = true;
this.setState(props);
},
wait,
options
);
public render() {
return <Component {...this.state} />;
}
public componentWillReceiveProps(props: TProps) {
this.shouldRender = false;
this.updateState(props);
}
public componentWillUnmount() {
this.updateState.cancel();
}
public shouldComponentUpdate() {
return this.shouldRender;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment