UNPKG

1.8 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @emails oncall+relay
8 *
9 * @format
10 */
11'use strict';
12
13var React = require('react');
14
15var areEqual = require("fbjs/lib/areEqual");
16
17var useMemo = React.useMemo,
18 useRef = React.useRef,
19 useState = React.useState;
20
21function useMemoVariables(variables) {
22 var _variablesChangedGene2;
23
24 // The value of this ref is a counter that should be incremented when
25 // variables change. This allows us to use the counter as a
26 // memoization value to indicate if the computation for useMemo
27 // should be re-executed.
28 var variablesChangedGenerationRef = useRef(0); // We mirror the variables to check if they have changed between renders
29
30 var _useState = useState(variables),
31 mirroredVariables = _useState[0],
32 setMirroredVariables = _useState[1];
33
34 var variablesChanged = !areEqual(variables, mirroredVariables);
35
36 if (variablesChanged) {
37 var _variablesChangedGene;
38
39 variablesChangedGenerationRef.current = ((_variablesChangedGene = variablesChangedGenerationRef.current) !== null && _variablesChangedGene !== void 0 ? _variablesChangedGene : 0) + 1;
40 setMirroredVariables(variables);
41 } // NOTE: We disable react-hooks-deps warning because we explicitly
42 // don't want to memoize on object identity
43 // eslint-disable-next-line react-hooks/exhaustive-deps
44
45
46 var memoVariables = useMemo(function () {
47 return variables;
48 }, [variablesChangedGenerationRef.current]);
49 return [memoVariables, (_variablesChangedGene2 = variablesChangedGenerationRef.current) !== null && _variablesChangedGene2 !== void 0 ? _variablesChangedGene2 : 0];
50}
51
52module.exports = useMemoVariables;
\No newline at end of file