How to use the react.useMemo 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 unicorn-utterances / unicorn-utterances / src / utils / a11y / usePopoverCombobox.js View on Github external
}

			if (kbEvent.code === "KeyA" && kbEvent.ctrlKey) {
				kbEvent.preventDefault();
				selectAll();
				return;
			}

			if (kbEvent.key === "Escape") {
				kbEvent.preventDefault();
				setExpanded(false);
			}
		}
	);

	const active = useMemo(() => {
		return internalArr[focusedIndex];
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [focusedIndex, internalArr, manuallyUpdateSelectedArrIndex]);

	// This will be empty if `enableSelect` is null
	const selectedArr = useMemo(
		() => internalArr.filter(item => item.selected),
		// eslint-disable-next-line react-hooks/exhaustive-deps
		[internalArr, manuallyUpdateSelectedArrIndex]
	);

	return {
		selected: selectedArr,
		active,
		comboBoxListRef,
		parentRef,
github jacobp100 / hooks-test / src / GraphView / hooks / useSelectionRectangle.js View on Github external
export default (ref, canvasOrigin, { onRectangleSelected } = {}) => {
  const [rectStart, setRectStart] = useState(null);
  const [rectEnd, setRectEnd] = useState(null);
  const [additive, setAdditive] = useState(false);
  const selectionRectangle = useMemo(
    () => createSelectionRectangle(additive, rectStart, rectEnd),
    [additive, rectStart, rectEnd]
  );

  const startSelectionRectangle = useCallback(
    e => {
      const graphCoords = getGraphCoordinatesForEvent(canvasOrigin, e);
      if (graphCoords != null) {
        setRectStart(graphCoords);
        setRectEnd(graphCoords);
        setAdditive(e.shiftKey);
      }
    },
    [setRectStart, setAdditive]
  );
github plgd-dev / cloud / http-gateway / web / src / containers / things / _things-resources-list.js View on Github external
export const ThingsResourcesList = ({
  data,
  onUpdate,
  onCreate,
  onDelete,
  deviceStatus,
  loading,
}) => {
  const { formatMessage: _ } = useIntl()

  const isUnregistered = deviceStatus === UNREGISTERED
  const greyedOutClassName = classNames({ 'grayed-out': isUnregistered })

  const columns = useMemo(
    () => [
      {
        Header: _(t.location),
        accessor: 'href',
        Cell: ({ value, row }) => {
          const {
            original: { di, href },
          } = row
          if (isUnregistered) {
            return <span>{value}</span>
          }
          return (
            <span> onUpdate({ di, href })}&gt;
              {value}
            </span>
          )
github netlify / staticgen / src / pages / index.js View on Github external
const sortedProjects = useMemo(() =&gt; {
    let count = 0
    return filteredProjects.sort((aObj, bObj) =&gt; {
      const aCurrent = aObj.stats[sort.field]
      const bCurrent = bObj.stats[sort.field]
      const a = sort.days ? aCurrent - (aObj.previousStats || {})[sort.field] || 0 : aCurrent
      const b = sort.days ? bCurrent - (bObj.previousStats || {})[sort.field] || 0 : bCurrent
      const types = ['number', 'string']
      if (a &amp;&amp; !b) return -1
      if (!a &amp;&amp; b) return 1
      if (a &amp;&amp; b) return compare(a, b, sort.reverse)
      return compare(aObj.stats[siteMeta.fallbackSortField], bObj.stats[siteMeta.fallbackSortField])
    })
  }, [filteredProjects, sort])

  const filters = useMemo(() =&gt; {
    return siteMeta.filters.map(filter =&gt; ({
      ...filter,
      values: sortBy(uniq(flatMap(projects, filter.field))),
    }))
  }, [projects, siteMeta.filters])

  const promoText = useMemo(() =&gt; {
    return allSiteMetadataMarkdownRemark.find(({ name }) =&gt; name === 'promo').html
  }, [allSiteMetadataMarkdownRemark])

  const renderProjects = () =&gt; {
    const list = sortedProjects.map(project =&gt; (
      <li>
        
      </li>
    ))
github SAP / ui5-webcomponents-react / packages / main / src / components / MessageBox / index.tsx View on Github external
case MessageBoxTypes.ERROR:
        return ;
      case MessageBoxTypes.INFORMATION:
        return ;
      case MessageBoxTypes.SUCCESS:
        return ;
      case MessageBoxTypes.WARNING:
        return ;
      case MessageBoxTypes.HIGHLIGHT:
        return ;
    }

    return null;
  }, [icon, type]);

  const titleToRender = useMemo(() =&gt; {
    if (title) {
      return title;
    }
    switch (type) {
      case MessageBoxTypes.CONFIRM:
        return 'Confirmation';
      case MessageBoxTypes.ERROR:
        return 'Error';
      case MessageBoxTypes.INFORMATION:
        return 'Information';
      case MessageBoxTypes.SUCCESS:
        return 'Success';
      case MessageBoxTypes.WARNING:
        return 'Warning';
      case MessageBoxTypes.HIGHLIGHT:
        return 'Highlight';
github bayesimpact / bob-emploi / frontend / client / src / components / phylactery.tsx View on Github external
const DiscussionBase: React.FC = (props): React.ReactElement =&gt; {
  const {children, headWidth = 75, isFastForwarded, isOneBubble, style,
    ...otherProps} = props
  const [isDiscussing, setDiscussing] = useState(false)
  const scrollSticker = useRef(null)
  const stickScrollToBottom = useCallback((): void =&gt; {
    scrollSticker.current &amp;&amp; scrollSticker.current.stick()
  }, [scrollSticker])
  const scrollableStyle = useMemo((): React.CSSProperties =&gt; ({
    display: 'flex',
    flexDirection: 'column-reverse',
    paddingBottom: 20,
    ...style,
  }), [style])
  const Container = isOneBubble ? DiscussionBubble : GrowingPhylactery

  return <div style="{scrollableStyle}">
    
    <img alt="{config.productName}" style="{{" src="{bobHeadImage}">
    
    </div>
github atomicpages / pretty-checkbox-react / src / components / BaseInput / BaseInput.tsx View on Github external
animation,
            disabled,
            locked,
            className,
            children,
            onChange,
            icon,
            bigger,
            type = 'checkbox',
            ...rest
        }: BaseInputProps,
        htmlRef: React.Ref
    ) =&gt; {
        const [iconType, memoizedIcon] = useMemoizedIcon(icon);

        const isDefault = React.useMemo(() =&gt; {
            return isDefaultStyle({
                icon,
                animation,
                isSwitch: !!(className &amp;&amp; className.includes('p-switch')),
            });
        }, [icon, animation, className]);

        return (
github elastic / kibana / x-pack / legacy / plugins / index_management / public / app / components / mappings_editor / mappings_state.tsx View on Github external
export const MappingsState = React.memo(({ children, onUpdate, defaultValue }: Props) => {
  const didMountRef = useRef(false);

  const parsedFieldsDefaultValue = useMemo(() => normalize(defaultValue.fields), [
    defaultValue.fields,
  ]);

  const { maxNestedDepth } = parsedFieldsDefaultValue;

  const canUseDefaultEditor = canUseMappingsEditor(maxNestedDepth);

  const initialState: State = {
    isValid: undefined,
    configuration: {
      defaultValue: defaultValue.configuration,
      data: {
        raw: {},
        format: () => ({} as Mappings),
      },
      validate: () => Promise.resolve(true),
github pathephone / pathephone-web / src / view / _pages / SearchQueryPage / styled / SearchQueryPageButton.jsx View on Github external
export const SearchQueryPageButton = ({ text, mod, onClick }: TProps) => {
  const modTestId = React.useMemo(() => {
    switch (mod) {
      case "save":
        return testId.SEARCH_QUERY_PAGE__SAVE_SEARCH_BUTTON;
      case "delete":
        return testId.SEARCH_QUERY_PAGE__DELETE_SEARCH_BUTTON;
      case "new-results":
        return testId.SEARCH_QUERY_PAGE__NEW_RESULTS_BUTTON;
      default:
        throw new TypeError();
    }
  }, [mod]);

  const modClassName = React.useMemo(() => {
    switch (mod) {
      case "save":
        return styles.SearchQueryPage__Button_save;
github conveyal / analysis-ui / lib / components / modifications-map / stop-layer.js View on Github external
export default function StopLayer(p) {
  const routeStops = React.useMemo(
    () =&gt; getUniqueStops(p.feed, p.modification),
    [p.feed, p.modification]
  )

  const showUnselected = !!p.unselectedColor

  const isSelected = s =&gt;
    p.modification.stops == null
      ? p.nullIsWildcard
      : p.modification.stops.includes(s.stop_id)

  return (
    &lt;&gt;
      {showUnselected &amp;&amp;
        routeStops
          .filter(s =&gt; !isSelected(s))