@render-props/throttle
Version:
A state container which limits the frequency with which setState can be called using `requestAnimationFrame`.
72 lines (57 loc) • 1.67 kB
JavaScript
var _interopRequireDefault = require('@babel/runtime/helpers/interopRequireDefault')
exports.__esModule = true
exports.default = void 0
var _react = _interopRequireDefault(require('react'))
var _propTypes = _interopRequireDefault(require('prop-types'))
var _throttle = _interopRequireDefault(require('./utils/throttle'))
/**
import Throttle from '@render-props/throttle'
function ThrottledBodyScroller () {
return (
<Throttle initialState={{scrollY: 0, gt30: false}}>
{({throttleState, state}) => (
<body
onScroll={
e => throttleState(
prevState => (
window.scrollY > 30
? {gt30: true, scrollY: window.scrollY}
: {gt30: false, scrollY: window.scrollY}
)
)
}
>
Greater than 30? {String(state.gt30)}
</body>
)}
</Throttle>
)
}
*/
const emptyObj = {}
class Throttle extends _react.default.Component {
constructor(props) {
super(props)
this._setState = (...args) => this.setState(...args)
this.state = props.initialState || emptyObj
this.throttleState = (0, _throttle.default)(this._setState)
this.throttleContext = {
throttleState: this.throttleState,
state: this.state,
}
}
componentWillUnmount() {
this.throttleState.cancel()
}
render() {
// It's ok to mutate this
this.throttleContext.state = this.state
return this.props.children(this.throttleContext)
}
}
exports.default = Throttle
Throttle.propTypes = {
children: _propTypes.default.func.isRequired,
initialState: _propTypes.default.object,
}