How to use the react.useCallback function in react

To help you get started, we’ve selected a few react examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Urigo / WhatsApp-Clone-Client-React / src / hooks / use-infinite-scroll.ts View on Github external
elem.addEventListener('scroll', handleScroll);

    return () => {
      elem!.removeEventListener('scroll', handleScroll);
    };
  }, [ref, handleScroll]);

  // loads more if fetching has started
  useEffect(() => {
    if (isFetching) {
      onLoadMore();
    }
  }, [isFetching, onLoadMore]);

  const stopFetching = useCallback(() => {
    setIsFetching(false);
  }, []);

  return [isFetching, stopFetching];
};
github Annihil / revolut-emergency / src / contexts / ChatContext.tsx View on Github external
const openTicket = useCallback(async () => {
    let res;
    try {
      res = await chatApi.post(chatRoutes.ticket) as null | { data: { id: string } };
    } catch (e) {
      return console.error(e.response);
    }

    console.log({ newTicket: res?.data });

    await getTickets();

    setCurrentChat(res!.data.id);
  }, []);

  const rateTicket = useCallback(async (rating: number) => {
    try {
      await chatApi.post(chatRoutes.ticketRate(currentChat!), { rating });
    } catch (e) {
      return console.error(e.response);
    }

    console.log('rated ticket', rating);

    await loadChatHistory();
    await getTickets();
    await loadMessages(currentChat!);
  }, [currentChat]);

  const getTickets = useCallback(async () => {
    let res;
    try {
github aredotna / ervell / react / components / UI / DropZoneUploader / index.js View on Github external
const DropZoneUploader = ({
  children,
  onUpload,
  onComplete,
}) => {
  const [mode, setMode] = useState('resting');

  const handleDrop = useCallback((acceptedFiles) => {
    if (acceptedFiles.length > 0) setMode('active');
  }, []);

  const handleErrors = (err) => {
    console.error(err);
    setMode('error');
  };

  const {
    getRootProps,
    getInputProps,
    isDragActive,
    open: openUploadDialog,
    acceptedFiles,
  } = useDropzone({
    onDrop: handleDrop,
github atlasmap / atlasmap / ui-react / packages / atlasmap-standalone / src / useSingleInputDialog.tsx View on Github external
onConfirmCb?: ConfirmCallback,
    onCancelCb?: CancelCallback
  ) => {
    onConfirm.current = onConfirmCb;
    onCancel.current = onCancelCb;
    setIsOpen(true);
  };
  const closeModal = () => setIsOpen(false);
  const handleTextInputChange = (
    value: string,
    event: FormEvent
  ) => {
    setValue(value);
    setIsValid((event.target as HTMLInputElement).reportValidity());
  };
  const handleConfirm = useCallback(() => {
    isValid && onConfirm.current && onConfirm.current(value);
    closeModal();
  }, [onConfirm, value, isValid]);
  const handleCancel = useCallback(() => {
    onCancel.current && onCancel.current();
    closeModal();
  }, [onCancel]);

  const modal = createPortal(
github ScottLogic / StockFlux / packages / stockflux-launcher / src / search-results / helpers / useChildWindow.js View on Github external
export default (name, document, cssUrl) => {
  const [state, dispatch] = useReducer(reducer, initialChildWindowState);
  const [window, setWindow] = useState(null);

  const injectNode = useCallback(
    node => {
      window
        .getWebWindow()
        .document.getElementsByTagName('head')[0]
        .appendChild(node.cloneNode(true));
    },
    [window]
  );

  const injectNodes = useCallback(
    nodes => {
      for (let node of nodes) {
        injectNode(node);
      }
    },
    [injectNode]
  );

  const inheritFromParent = useCallback(() => {
    const parentStyles = document.getElementsByTagName('style');
    const parentScripts = document.getElementsByTagName('script');

    injectNodes(parentStyles);
    injectNodes(parentScripts);
  }, [document, injectNodes]);
github tresko / react-datepicker / packages / styled / lib / index.esm.js View on Github external
(o && !i && l > 1 && le(t, o, Q(o, l - 2))) ||
            (a && a(t))
          )
        })({
          date: e,
          minBookingDate: d,
          maxBookingDate: l,
          startDate: a,
          endDate: o,
          minBookingDays: g,
          isDateBlockedFn: v,
        })
      },
      [d, l, a, o, g, v],
    ),
    H = n(
      function(e) {
        return !!R && ce(e, R)
      },
      [R],
    ),
    E = n(
      function(e) {
        return (function(e) {
          var t = e.date,
            r = e.startDate,
            n = e.endDate,
            a = e.isDateBlocked,
            o = e.hoveredDate,
            i = e.minBookingDays
          return o && i > 1 && e.exactMinBookingDays && le(t, o, Q(o, i - 1))
            ? _(o, Q(o, i - 1)).reduce(function(e, t) {
github 44uk / nem2-dev-ui / src / pages / Node / index.tsx View on Github external
export const Node: React.FC = () => {
  const gwContext = useContext(GatewayContext)
  const httpContext = useContext(HttpContext)

  const { nodeHttp, diagnosticHttp } = httpContext.httpInstance
  const { nodeData, handler, loading, error } = useNodeData({ nodeHttp, diagnosticHttp })

  const [output, setOutput] = useState("")

  useEffect(() => {
    if(nodeData) setOutput(stringifyNodeData(nodeData))
  }, [nodeData])

  const submit = useCallback(() => {
    handler()
  }, [handler])

  return (
<div>
  <fieldset>
    <legend>Node</legend>
    <div>
      <p>
      { true
        ? <a rel="noopener noreferrer" href="{`${gwContext.url}/node/info`}">{`${gwContext.url}/node/info`}</a>
        : <span>{`${gwContext.url}/block/`}</span>
      }
      </p></div></fieldset></div>
github plouc / nivo / packages / scatterplot / src / ScatterPlotCanvas.js View on Github external
])

    const { showTooltipFromEvent, hideTooltip } = useTooltip()

    const getNodeFromMouseEvent = useCallback(
        event => {
            const [x, y] = getRelativeCursor(canvasEl.current, event)
            if (!isCursorInRect(margin.left, margin.top, innerWidth, innerHeight, x, y)) return null

            const nodeIndex = delaunay.find(x - margin.left, y - margin.top)
            return nodes[nodeIndex]
        },
        [canvasEl, margin, innerWidth, innerHeight, delaunay]
    )

    const handleMouseHover = useCallback(
        event => {
            const node = getNodeFromMouseEvent(event)
            setCurrentNode(node)

            if (node) {
                showTooltipFromEvent(React.createElement(tooltip, { node }), event)
                if (currentNode && currentNode.id !== node.id) {
                    onMouseLeave && onMouseLeave(currentNode, event)
                    onMouseEnter && onMouseEnter(node, event)
                }
                if (!currentNode) {
                    onMouseEnter && onMouseEnter(node, event)
                }
                onMouseMove && onMouseMove(node, event)
            } else {
                hideTooltip()
github jitsucom / jitsu / configurator / frontend / src / ui / pages / SourcesPage / partials / SourceEditor / SourceEditorDestinations.tsx View on Github external
async() =&gt; await services.storageService.get('destinations', projectId)
  );

  const destinationsList = useMemo(() =&gt; destinations?.destinations?.map((dst: DestinationData) =&gt; {
    const reference = destinationsReferenceMap[dst._type]
    return {
      id: dst._uid,
      disabled: reference.syncFromSourcesStatus === 'coming_soon' || reference.syncFromSourcesStatus === 'not_supported',
      title: <b>{reference.displayName}</b>: {destinationsUtils.getTitle(dst)},
      description: <i>{getDescription(reference)}</i>
    };
  }) ?? [], [destinations?.destinations]);

  const preparedInitialValue = useMemo(() =&gt; initialValues?.destinations ?? [], [initialValues]);

  const handleItemChange = useCallback((items: string[]) =&gt; {
    const beenTouched = JSON.stringify(items) !== JSON.stringify(initialValues.destinations)

    handleTouchAnyField(beenTouched);
  }, [initialValues, handleTouchAnyField])

  return (
    &lt;&gt;
      {SOURCE_CONNECTED_DESTINATION}

      <form name="connected-destinations">
        Please, choose at least one source.<p></p>}
          initialValues={preparedInitialValue}</form>
github accordproject / markdown-editor / src / SlateAsInputEditor / index.js View on Github external
return <code>{children}</code>;
      case 'error':
        return <span>{children}</span>;
      default:
        return next();
    }
  }, []);

  /**
  * Returns true if the editor should allow an edit. Edits are allowed for all
  * text unless the lockText parameter is set in the state of the editor, in which
  * case the decision is delegated to the PluginManager.
  * @param {Editor} editor the Slate Editor
  * @param {string} code the type of edit requested
  */
  const isEditable = useCallback((editor, code) =&gt; {
    if (editor.props.readOnly) { return false; }
    if (editor.props.lockText) {
      const pluginManager = new PluginManager(plugins);
      return pluginManager.isEditable(editor, code);
    }

    return true;
  }, [plugins]);

  /**
  * On backspace, if at the start of a non-paragraph, convert it back into a
  * paragraph node.
  *
  * @param {Event} event
  * @param {Editor} editor
  * @param {Function} next