Created
August 31, 2018 14:21
-
-
Save fabien0102/a3524e097b3c83e90460d138b59e666c to your computer and use it in GitHub Desktop.
Debounce component render
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 { 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