How to use the useCallback function from react

Find comprehensive JavaScript react.useCallback code examples handpicked from public code repositorys.

3
4
5
6
7
8
9
10
11
const PropTypes = require('prop-types');
const classnames = require('classnames');
const styles = require('./styles');

const Button = React.forwardRef(({ className, href, disabled, children, ...props }, ref) => {
    const onKeyDown = React.useCallback((event) => {
        if (typeof props.onKeyDown === 'function') {
            props.onKeyDown(event);
        }
fork icon129
star icon501
watch icon31

+ 3 other calls in file

33
34
35
36
37
38
39
40
41
42
const [, , , toggleFullscreen] = useFullscreen();
const [casting, setCasting] = React.useState(() => {
    return chromecast.active && chromecast.transport.getCastState() === cast.framework.CastState.CONNECTED;
});
const [immersed, setImmersed] = React.useState(true);
const setImmersedDebounced = React.useCallback(debounce(setImmersed, 3000), []);
const [subtitlesMenuOpen, , closeSubtitlesMenu, toggleSubtitlesMenu] = useBinaryState(false);
const [infoMenuOpen, , closeInfoMenu, toggleInfoMenu] = useBinaryState(false);
const [videosMenuOpen, , closeVideosMenu, toggleVideosMenu] = useBinaryState(false);
const [error, setError] = React.useState(null);
fork icon129
star icon1
watch icon0

+ 55 other calls in file

13
14
15
16
17
18
19
20
21
22
const onPropChangedRef = useLiveRef(props.onPropChanged);
const onSubtitlesTrackLoadedRef = useLiveRef(props.onSubtitlesTrackLoaded);
const onImplementationChangedRef = useLiveRef(props.onImplementationChanged);
const videoElementRef = React.useRef(null);
const videoRef = React.useRef(null);
const dispatch = React.useCallback((action) => {
    if (action && action.type === 'command' && action.commandName === 'load' && action.commandArgs) {
        const Video = selectVideoImplementation(action.commandArgs);
        if (videoRef.current === null || videoRef.current.constructor !== Video) {
            dispatch({ type: 'command', commandName: 'destroy' });
fork icon129
star icon0
watch icon0

26
27
28
29
30
31
32
33
34
35
const [inputsModalOpen, openInputsModal, closeInputsModal] = useBinaryState(false);
const [addonModalOpen, openAddonModal, closeAddonModal] = useBinaryState(false);
const [selectedMetaItem, setSelectedMetaItem] = React.useState(() => {
    return getMetaItemAtIndex(discover.catalog_resource, 0);
});
const metaItemsOnFocusCapture = React.useCallback((event) => {
    const metaItem = getMetaItemAtIndex(discover.catalog_resource, event.target.dataset.index);
    setSelectedMetaItem(metaItem);
}, [discover.catalog_resource]);
const metaItemOnClick = React.useCallback((event) => {
fork icon129
star icon0
watch icon1

+ 3 other calls in file

52
53
54
55
56
57
58
59
60
61
        subtitlesBackgroundColor: null,
        subtitlesOutlineColor: null
    }
);
const videoRef = React.useRef(null);
const dispatch = React.useCallback((args) => {
    if (videoRef.current !== null) {
        videoRef.current.dispatch(args);
    }
}, []);
fork icon129
star icon0
watch icon0

+ 49 other calls in file

62
63
64
65
66
67
68
69
70
71
): React.Node {
  const focusGuideRef = React.useRef<React.ElementRef<
    typeof ReactNative.View,
  > | null>(null);

  const setDestinations = React.useCallback(
    (destinations: (?React.ElementRef<HostComponent<mixed>>)[]) => {
      const dests: number[] = (destinations || [])
        .map(ReactNative.findNodeHandle)
        .filter(Boolean);
fork icon108
star icon594
watch icon27

61
62
63
64
65
66
67
68
69
70
    });
}, [metaDetails]);
const seasonOnSelect = React.useCallback((event) => {
    setSeason(event.value);
}, [setSeason]);
const renderBackgroundImageFallback = React.useCallback(() => null, []);
return (
    <div className={styles['metadetails-container']}>
        <HorizontalNavBar
            className={styles['nav-bar']}
fork icon129
star icon501
watch icon31

+ 7 other calls in file

288
289
290
291
292
293
294
295
296
297
298
    return () => void deleteItem(key);
  }, [setItem, deleteItem, itemKey, initialEntered, disabled]);
  return {
    itemRef,
    state,
    toggle: react.useCallback(toEnter => toggle(key, toEnter), [toggle, key])
  };
};


const _excluded$1 = ["itemKey", "initialEntered"];
fork icon4
star icon84
watch icon0

1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
    ref.current = true;
    return () => {
      ref.current = false;
    };
  }, []);
  return React.useCallback(() => ref.current, [ref]);
}
const useRemaining = ({
  instance,
  id,
fork icon1
star icon54
watch icon1

1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
  dispatchTransition(props.onShow);
};
const hide2 = () => {
  dispatchTransition(props.onHide);
};
const domElementCb = React.useCallback((node) => {
  if (node !== null) {
    domElementRef.current = node;
    onMount();
  }
fork icon1
star icon54
watch icon1

+ 5 other calls in file

12
13
14
15
16
17
18
19
20
21
const routeFocused = useRouteFocused();
const [slidingVolume, setSlidingVolume] = React.useState(null);
const resetVolumeDebounced = React.useCallback(debounce(() => {
    setSlidingVolume(null);
}, 100), []);
const onSlide = React.useCallback((volume) => {
    resetVolumeDebounced.cancel();
    setSlidingVolume(volume);
    if (typeof onVolumeChangeRequested === 'function') {
        onVolumeChangeRequested(volume);
fork icon129
star icon0
watch icon1

+ 5 other calls in file

336
337
338
339
340
341
342
343
344
345
  items: [],
  hoverIndex: -1,
  sorted: false
});
var mutableState = stateRef.current;
var updateItems = react.useCallback(function (item, isMounted) {
  var items = mutableState.items;
  if (!item) {
    mutableState.items = [];
  } else if (isMounted) {
fork icon48
star icon881
watch icon6

+ 3 other calls in file

1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
var useCancelAllRunningApiCalls = function useCancelAllRunningApiCalls(reducerName) {
  if (!reducerName) checkKeyWithMessage(reducerName, 'string', 'useCancelAllRunningApiCalls(`reducerkey`) : Expected a valid reducer key');
  var store = reactRedux.useStore();
  var dispatch = reactRedux.useDispatch();


  var _callback = React.useCallback(function () {
    var dontCancelKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var state = store.getState()[reducerName];
    var actions = Object.entries(state).reduce(function (acc, _ref25) {
      var _ref26 = _slicedToArray(_ref25, 2),
fork icon6
star icon9
watch icon3

+ 40 other calls in file

1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
    previousCallbackData.delete(_key);
    initialRender.delete(_key);
    previousDependencyArrayData.delete(_key);
  };
}, []);
var equalityCheckFunction = React.useCallback(function (e, f) {
  var _isEqual = typeof e.isEqualCheck === 'undefined' ? isEqual(e.data, f.data) : e.isEqualCheck;

  if ((!_isEqual || initialRender.get(_key)) && typeof callbackSuccess === 'function') {
    initialRender.set(_key, false);
fork icon6
star icon9
watch icon3

+ 73 other calls in file

1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
        nextPage: noop__default['default'],
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        prevPage: noop__default['default'],
    },
}), state = _a[0], dispatch = _a[1];
state.pagination.nextPage = React.useCallback(function () {
    dispatch({ type: "NEXT_PAGE" });
}, [dispatch]);
state.pagination.prevPage = React.useCallback(function () { return dispatch({ type: "PREV_PAGE" }); }, [dispatch]);
React.useEffect(function () {
fork icon1
star icon1
watch icon0

+ 13 other calls in file

19
20
21
22
23
24
25
26
27
28
function SwapTokenListDialog(props) {
    var open = props.open, onClose = props.onClose, activeAddress = props.activeAddress, onSelect = props.onSelect, disabledAddresses = props.disabledAddresses;
    var tokens = useCurrencyList_1["default"]();
    var _a = react_2.useState(""), searchQuery = _a[0], setSearchQuery = _a[1];
    // eslint-disable-next-line react-hooks/exhaustive-deps
    var handleSearch = react_2.useCallback(throttle_debounce_1.debounce(200, false, function (e) {
        var query = e.target.value;
        setSearchQuery(query);
    }), []);
    var activeToken = react_2.useMemo(function () { return tokens.find(function (token) { return token.address === activeAddress; }); }, [tokens, activeAddress]);
fork icon0
star icon0
watch icon1

+ 2 other calls in file

153
154
155
156
157
158
159
160
161
162
    element.current.style.display = 'block'
    await animateBack(element.current)
  }
}))

const handleSwipeReleased = React.useCallback(async (element, speed) => {
  if (swipeAlreadyReleased.current) { return }
  swipeAlreadyReleased.current = true

  // Check if this is a swipe
fork icon0
star icon0
watch icon0

140
141
142
143
144
145
146
147
148
149
  isActive = _ref2$isActive === void 0 ? false : _ref2$isActive,
  dotColorInactive = _ref2.dotColorInactive,
  dotColorActive = _ref2.dotColorActive,
  DotCustom = _ref2.dot,
  onClick = _ref2.onClick;
var handleClick = React.useCallback(function () {
  onClick(index);
}, [index, onClick]);
return /*#__PURE__*/React__default.createElement(DotWrapper, {
  onClick: handleClick
fork icon0
star icon0
watch icon0

+ 11 other calls in file

156
157
158
159
160
161
162
163
164
165
/**
 * Creates a ref function that, when called, hydrates the provided
 * external ref and VisualElement.
 */
function useMotionRef(visualState, visualElement, externalRef) {
    return React.useCallback((instance) => {
        instance && visualState.mount && visualState.mount(instance);
        if (visualElement) {
            instance
                ? visualElement.mount(instance)
fork icon0
star icon0
watch icon1

+ 4 other calls in file

783
784
785
786
787
788
789
790
791
792
function useLatestFunc(fn) {
  const ref = react.useRef(fn);
  react.useEffect(() => {
    ref.current = fn;
  });
  const callbackFn = react.useCallback((...args) => {
    ref.current(...args);
  }, []);
  return fn ? callbackFn : fn;
}
fork icon0
star icon0
watch icon1

+ 7 other calls in file