'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

exports['default'] = useFrameState;

var _react = require('react');

var React = _interopRequireWildcard(_react);

var _raf = require('raf');

var _raf2 = _interopRequireDefault(_raf);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function useFrameState(defaultValue) {
    var _React$useState = React.useState(defaultValue),
        _React$useState2 = (0, _slicedToArray3['default'])(_React$useState, 2),
        value = _React$useState2[0],
        setValue = _React$useState2[1];

    var frameRef = (0, _react.useRef)(null);
    var batchRef = (0, _react.useRef)([]);
    var destroyRef = (0, _react.useRef)(false);
    React.useEffect(function () {
        return function () {
            destroyRef.current = true;
            _raf2['default'].cancel(frameRef.current);
        };
    }, []);
    function setFrameValue(updater) {
        if (destroyRef.current) {
            return;
        }
        if (frameRef.current === null) {
            batchRef.current = [];
            frameRef.current = (0, _raf2['default'])(function () {
                frameRef.current = null;
                setValue(function (prevValue) {
                    var current = prevValue;
                    batchRef.current.forEach(function (func) {
                        current = func(current);
                    });
                    return current;
                });
            });
        }
        batchRef.current.push(updater);
    }
    return [value, setFrameValue];
}
module.exports = exports['default'];