3 ms·
I write a LOT of React code, and I abuse closures daily The statement you quote is overly dramatic, and it takes maybe 5 minutes to clearly explain the concept
by arenaninja 8y ago
I write a LOT of React code, and I abuse closures daily
The statement you quote is overly dramatic, and it takes maybe 5 minutes to clearly explain the concept to someone that grasps the basic language syntax. The usefulness is more difficult to lay out clearly
Where it comes up very often for me is when using mapStateToPropsFactory from react-redux, like this:
// a closure for ownProps is created
// the factory is not invoked everytime the component changes props
const mapStateToPropsFactory = (_, ownProps) => {
const { uniqueId } = ownProps;
return function mapStateToProps(state) {
return {
usefulThing: state.usefulThings[uniqueId],
ping: state.pong,
}
}
}
If you don't do things this way, react-redux loses a lot of optimizations for connected components that have an ownProps argument