How to use the preact/hooks.useMemo function in preact

To help you get started, we’ve selected a few preact 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 hypothesis / lms / lms / static / scripts / frontend_apps / components / DialogTestsAndExamples.js View on Github external
function FilePickerDialog({ onClose }) {
  const [dialogState, setDialogState] = useState('');
  const [selectedFile, setSelectedFile] = useState();

  const files = useMemo(() => {
    const base = new Date(); // now
    const f = [];
    for (let i = 0; i < 100; i++) {
      f.push({
        display_name: `File ${i.toString().padStart(3, '0')}`,
        updated_at: new Date(base - i * (86400 * 1000)).toISOString(), // ms in a day
      });
    }
    return f;
  }, []);

  return (
github GoogleChrome / lighthouse-ci / packages / server / src / ui / hooks / use-api-data.jsx View on Github external
export function useBranchBuilds(projectId, branch, options = {}) {
  // Construct this options object in a `useMemo` to prevent infinitely re-requesting.
  const getBuildsOptions = useMemo(() => ({branch, limit: options.limit}), [branch, options.limit]);
  return useApiData('getBuilds', [projectId, getBuildsOptions]);
}
github GoogleChrome / lighthouse-ci / packages / server / src / ui / routes / build-view / build-view.jsx View on Github external
/** @type {LH.Result|undefined} */
  let lhr;
  /** @type {LH.Result|undefined} */
  let baseLhr;
  /** @type {Error|undefined} */
  let lhrError;

  try {
    lhr = useMemo(() => run && JSON.parse(run.lhr), [run]);
  } catch (err) {
    lhrError = err;
  }

  try {
    baseLhr = useMemo(() => baseRun && JSON.parse(baseRun.lhr), [baseRun]);
  } catch (err) {
    lhrError = err;
  }

  // Attach the LHRs to the window for easy debugging.
  useEffect(() => {
    // @ts-ignore
    window.__LHR__ = lhr;
    // @ts-ignore
    window.__BASE_LHR__ = baseLhr;
  }, [lhr, baseLhr]);

  if (!run || !lhr) {
    return (
      
        <h1>No runs for build</h1>
github hypothesis / client / src / sidebar / components / tag-list.js View on Github external
function TagList({ annotation, serviceUrl, settings, tags }) {
  const renderLink = useMemo(
    // Show a link if the authority of the user is not 3rd party
    () =&gt; !isThirdPartyUser(annotation.user, settings.authDomain),
    [annotation, settings]
  );

  /**
   * Returns a uri link for a specific tag name.
   * @param {string} tag
   * @return {string}
   */
  const createTagSearchURL = tag =&gt; {
    return serviceUrl('search.tag', { tag: tag });
  };

  return (
    <ul aria-label="Annotation tags"></ul>
github hypothesis / client / src / sidebar / components / search-status-bar.js View on Github external
* @type {Boolean}
     * 0 - n annotations are currently "selected", by, e.g. clicking on highlighted
     * text in the host page, direct-linking to an annotation, etc. Superseded by
     * `filtered` mode.
     */
    selected: (() => {
      if (directLinkedGroupFetchFailed) {
        return true;
      }
      return (
        !!selectionMap && Object.keys(selectionMap).length > 0 && !filterQuery
      );
    })(),
  };

  const visibleCount = useMemo(() => {
    return countVisibleAnns(thread);
  }, [thread]);

  // Each "mode" has corresponding descriptive text about the number of
  // matching/applicable annotations and, sometimes, a way to clear the
  // filter
  const modeText = {
    filtered: (() => {
      switch (visibleCount) {
        case 0:
          return `No results for "${filterQuery}"`;
        case 1:
          return '1 search result';
        default:
          return `${visibleCount} search results`;
      }
github hypothesis / client / src / sidebar / components / group-list.js View on Github external
const currentGroups = useStore(store => store.getCurrentlyViewingGroups());
  const featuredGroups = useStore(store => store.getFeaturedGroups());
  const myGroups = useStore(store => store.getMyGroups());
  const focusedGroup = useStore(store => store.focusedGroup());
  const userid = useStore(store => store.profile().userid);

  const myGroupsSorted = useMemo(() => groupsByOrganization(myGroups), [
    myGroups,
  ]);

  const featuredGroupsSorted = useMemo(
    () => groupsByOrganization(featuredGroups),
    [featuredGroups]
  );

  const currentGroupsSorted = useMemo(
    () => groupsByOrganization(currentGroups),
    [currentGroups]
  );

  const { authDomain } = settings;
  const canCreateNewGroup = userid && !isThirdPartyUser(userid, authDomain);
  const newGroupLink = serviceUrl('groups.new');

  // The group whose submenu is currently open, or `null` if no group item is
  // currently expanded.
  //
  // nb. If we create other menus that behave similarly in future, we may want
  // to move this state to the `Menu` component.
  const [expandedGroup, setExpandedGroup] = useState(null);

  let label;
github GoogleChrome / lighthouse-ci / packages / server / src / ui / hooks / use-api-data.jsx View on Github external
export function useOptionalBuildRepresentativeRuns(projectId, buildId, url) {
  const isUrlDefined = url !== undefined;
  // Construct this options object in a `useMemo` to prevent infinitely re-requesting.
  const getRunsOptions = useMemo(
    () => (url ? {representative: true, url} : {representative: true}),
    [url]
  );

  return useApiData(
    'getRuns',
    projectId && buildId && isUrlDefined ? [projectId, buildId, getRunsOptions] : undefined
  );
}
github preactjs / preact / demo / people / router.tsx View on Github external
export const Link: FunctionalComponent = props =&gt; {
  const router = useRouter()

  const classProps = [props.class, props.className]
  const originalClasses = useMemo(() =&gt; {
    const classes = []
    for (const prop of classProps) if (prop) classes.push(...prop.split(/\s+/))
    return classes
  }, classProps)

  const activeClass = useMemo(() =&gt; {
    if (!props.active || props.href == null) return undefined
    const href = props.href.split("/").filter(Boolean)
    const path = props.href[0] === "/" ? [...router.match, ...router.path] : router.path
    const isMatch = href.every((dir, i) =&gt; dir === path[i])
    if (isMatch) return props.active === true ? "active" : props.active
  }, [originalClasses, props.active, props.href, router.match, router.path])

  const classes = activeClass == null ? originalClasses : [...originalClasses, activeClass]

  const getHref = useCallback(() =&gt; {
github GoogleChrome / lighthouse-ci / packages / server / src / ui / routes / project-dashboard / project-graphs.jsx View on Github external
export const ProjectGraphs = props => {
  const {project, builds, branch: overrideBranch} = props;
  const branch =
    overrideBranch ||
    (!builds.length || builds.some(build => build.branch === 'master')
      ? 'master'
      : builds[0].branch);
  const buildIds = useMemo(
    () =>
      builds
        .filter(build => build.branch === branch)
        .sort((a, b) => new Date(b.runAt).getTime() - new Date(a.runAt).getTime())
        .map(build => build.id)
        .slice(0, 20),
    [builds, branch]
  );
  const [loadingState, stats] = useBuildStatistics(project.id, buildIds);
  const statsWithBuildsUnfiltered = augmentStatsWithBuilds(stats, builds);
  const statsWithBuilds =
    statsWithBuildsUnfiltered &&
    statsWithBuildsUnfiltered
      .filter(stat => stat.build.branch === branch)
      .filter(stat => !props.runUrl || stat.url === props.runUrl);
github nickvdyck / webtty / src / WebTty.UI / services / useWebTty.ts View on Github external
const useWebTty = (endpoint: string): WebTtyConnection =&gt; {
    const [dataStream, sendMessage] = useWebSocket(endpoint, {
        binaryType: "arraybuffer",
    })
    const [state, dispatch] = useReducer(terminalReducer, { tabId: undefined })

    const actions = useMemo(() =&gt; {
        const dispatchCommand = (command: Messages): void =&gt; {
            const serialized = serializeCommands(command)
            sendMessage(serialized)
        }

        return {
            openNewTab: openNewTab(dispatchCommand),
            resizeTerminal: resizeTerminal(dispatchCommand),
            writeStdIn: writeStdIn(dispatchCommand),
        }
    }, [sendMessage])

    const messageStream = useMemo((): AsyncQueue =&gt; {
        const eventStream = deserializeMessages(dataStream)
        const queue = AsyncQueue.from(eventStream)
        return queue