Last active
May 4, 2017 00:48
-
-
Save mgtitimoli/0d6ccee575d5bd22ac1a1a4be6a062a4 to your computer and use it in GitHub Desktop.
shouldComponentUpdate and componentWIllReceiveProps done well
This file contains hidden or 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
// @flow | |
import shallowEqual from "../shallowEqual"; | |
type OnPropsChanged<Props> = ( | |
props: Props, | |
component: React$Component<*, Props, *> | |
) => mixed; | |
const updateIfPropsChanged = <Props: Object, State: void | Object>( | |
component: React$Component<*, Props, State>, | |
onPropsChanged?: OnPropsChanged<Props> | |
) => { | |
let propsChanged = false; | |
const checkIfPropsChanged = props => { | |
propsChanged = !shallowEqual(props, component.props); | |
}; | |
const shouldComponentUpdate = (props: Props, state: State) => { | |
if (state !== component.state) { | |
return true; | |
} | |
if (!component.componentWillReceiveProps) { | |
checkIfPropsChanged(props); | |
} | |
return propsChanged; | |
}; | |
const componentWillReceiveProps = (props: Props) => { | |
checkIfPropsChanged(props); | |
// onPropsChanged can't never be undefined here (when it is, we are not | |
// returning componentWillReceiveProps) but we need to check it as flow | |
// is not detecting this fact | |
if (propsChanged && onPropsChanged !== undefined) { | |
onPropsChanged(props, component); | |
} | |
}; | |
return onPropsChanged !== undefined | |
? {componentWillReceiveProps, shouldComponentUpdate} | |
: {shouldComponentUpdate}; | |
}; | |
export default updateIfPropsChanged; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment