How to use the react.useRef 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 Chalarangelo / furl / src / utilities / useEffectOnUpdate.js View on Github external
function useEffectOnUpdate (fn, params) {
  const firstUpdate = useRef(true);

  // Only run if this is not the first update.
  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }
    fn();
  }, params);
}
github DanielCKennedy / playallaudio / src / components / SearchContent.tsx View on Github external
const SearchContent: React.FC = ({ source, artistSearchId, spotifyToken }) => {
  const classes = useStyles();
  const [searchText, setSearchText] = useState("");
  const [artistList, setArtistList] = useState([]);
  const [trackList, setTrackList] = useState([]);
  const [soundcloudTrackList, setSoundcloudTrackList] = useState([]);
  const [spotifyTrackList, setSpotifyTrackList] = useState([]);
  const [soundcloudArtistList, setSoundcloudArtistList] = useState([]);
  const [spotifyArtistList, setSpotifyArtistList] = useState([]);
  const lastArtistPromiseSoundcloud = useRef();
  const lastArtistPromiseSpotify = useRef>();
  const lastTrackPromiseSoundcloud = useRef();
  const lastTrackPromiseSpotify = useRef>();

  useEffect(() => {
    SOUNDCLOUD_CLIENT_ID && soundcloud.initialize({
      client_id: SOUNDCLOUD_CLIENT_ID
    });

    // unfocus text field when user presses enter
    window.addEventListener("keydown", onEnterPress);

    return () => {
      window.removeEventListener("keydown", onEnterPress);
    }
  }, []);

  useEffect(() => {
github rmolinamir / hero-slider / src / Slider / HeroSlider.tsx View on Github external
const [delayTimeout, setDelayTimeout] = React.useState()
  const [slidingTimeout, setSlidingTimeout] = React.useState()

  const [autoplayHandlerTimeout, setAutoplayHandlerTimeout] = React.useState()
  // const [autoplayInstance] = React.useState(React.useMemo(() => {
  //   return new IntervalTimer(autoplay, settings.autoplayDuration + slidingTimeoutDuration)
  // }, []))
  const autoplayInstanceRef = React.useRef((React.useMemo(() => {
    return new IntervalTimer(autoplay, settings.autoplayDuration + slidingTimeoutDuration)
  }, [])))
  const autoplayInstance = autoplayInstanceRef.current

  /**
   * Slider reference object to calculate its dimensions.
   */
  const sliderRef = React.useRef(null)
  const [sliderDimensions, setSliderDimensions] = React.useState({})

  const setSliderDimensionsHandler = (): void => {
    const sliderDimensions: ISliderDimensions = {
      width: sliderRef.current ? sliderRef.current.clientWidth : undefined,
      height: sliderRef.current ? sliderRef.current.clientHeight : undefined
    }
    setSliderDimensions(sliderDimensions)
  }

  /**
   * `onTouchStartHandler` sets the initial coordinates of the touch event.
   */
  const onTouchStartHandler = (event: React.TouchEvent) => {
    const initialX = event.touches[0].clientX
    const initialY = event.touches[0].clientY
github josephluck / internote / ui / styles / editor.tsx View on Github external
/**
   * Derived state
   */
  const selectedText = getSelectedText(value);
  const shortcutSearch = getCurrentFocusedWord(value).filter(isShortcut);
  // TODO: hack as per https://github.com/ianstormtaylor/slate/issues/2927
  const shortcutSearchRef = useRef(shortcutSearch);
  shortcutSearchRef.current = shortcutSearch;

  /**
   * Refs
   */
  const editor = React.useRef();
  const scrollWrap = React.useRef();
  const scrollRef = React.useRef>();
  const preventScrollListener = React.useRef(false);
  const focusedNodeKey = React.useRef();
  const isMouseDown = React.useRef(false);
  const snippetInsertionIndicatorRef = React.useRef();

  /**
   * Replace value state in response to props
   */
  React.useEffect(() => {
    setValue(getValueOrDefault(initialValue));
  }, [id, overwriteCount]);

  /**
   * Emit changes to parent when value changes
   */
  const isFirst = React.useRef(true);
github hackoregon / civic / packages / 2019-disaster-game / src / components / atoms / OrbManager.js View on Github external
playSFX,
  taskPhase,
  activeTaskIndex,
  requiredItem
} = {}) => {
  const [hasInitialized, setHasInitialized] = useState(false);
  const [orbModels, setOrbModelsState] = useState([]);
  const [touchedOrbs, setTouchedOrb] = useState([]);
  const [completedOrbs, setCompletedOrbs] = useState([]);
  const [orbsZIndex, setOrbsZIndex] = useState([]);
  // tick is used to modulate movement based on an incrementing value
  const [tick, setTick] = useState(0);
  const [badKitItemTypesPlayed, setBadKitItemTypesPlayed] = useState({});

  // the boundaries of the OrbManagers area
  const boundsRef = useRef();
  const bounds = useBounds(boundsRef);
  const prevBounds = usePrevious(bounds);
  const prevTaskPhase = usePrevious(taskPhase);
  const prevActiveTaskIndex = usePrevious(activeTaskIndex);

  /* Generate new orbModels when the interface bounds change, usually only on load. Most often, generate new orbModels when switching between voting and solving. This catalyzes orb data and placement */
  useLayoutEffect(() => {
    const newTaskPhase = prevTaskPhase !== taskPhase && !!bounds.width;

    const newBounds =
      prevBounds && !prevBounds.width && bounds.width && !hasInitialized;

    const resetForSaveYourself =
      prevActiveTaskIndex !== activeTaskIndex && activeTaskIndex === 1;

    if (newBounds || newTaskPhase || resetForSaveYourself) {
github Royal-Navy / standards-toolkit / packages / react-component-library / src / fragments / Masthead / Masthead.tsx View on Github external
export const Masthead: React.FC = ({
  homeLink,
  LinkComponent = Link,
  Logo = DefaultLogo,
  navItems,
  notifications,
  onSearch,
  searchPlaceholder = '',
  title,
  hasUnreadNotification,
  user,
}) => {
  const [showSearch, setShowSearch] = useState(false)
  const [showNotifications, setShowNotifications] = useState(false)
  const searchButtonRef = useRef(null)
  const mastheadContainerRef = useRef(null)
  const [containerWidth, setContainerWidth] = useState(0)

  const toggleSearch = (
    event: React.MouseEvent
  ) => {
    event.currentTarget.blur()
    const newShowSearch = !showSearch

    // if opening the searchbar then get the container width and set that
    // as the width of the searchbar so that it does not spill
    // over to other parts of the page, such as the sidebar.
    if (newShowSearch === true) {
      setContainerWidth(mastheadContainerRef.current.offsetWidth)
    }
github streamr-dev / streamr-platform / app / src / editor / shared / hooks / useSelection.jsx View on Github external
if (!selection.has(id)) { return selection }
            const newSelection = new Set(selection)
            newSelection.delete(id)
            return newSelection
        })
    ), [setSelection])

    const only = useCallback((id) => (
        setSelection(new Set([id]))
    ), [setSelection])

    const none = useCallback(() => (
        setSelection(new Set())
    ), [setSelection])

    const selectionRef = useRef()
    selectionRef.current = selection

    const current = useCallback(() => (
        selectionRef.current
    ), [selectionRef])

    const isEmpty = useCallback(() => (
        selectionRef.current.size === 0
    ), [selectionRef])

    const has = useCallback((id) => (
        selectionRef.current.has(id)
    ), [selectionRef])

    const last = useCallback(() => (
        [...selectionRef.current][0]
github ShizukuIchi / fake-screen / src / hooks / useTimeout.js View on Github external
const useTimeout = (ms = 0, fn = () => {}, args = []) => {
  const timeoutRef = useRef();
  function start() {
    timeoutRef.current = setTimeout(fn.bind(null, args), ms);
  }
  function clear() {
    clearTimeout(timeoutRef.current);
  }
  function reset() {
    clear();
    start();
  }
  useEffect(() => {
    start();
    return clear;
  }, []);

  return reset;
github argoproj / argo-cd / ui / src / app / shared / components / expandable / expandable.tsx View on Github external
export const Expandable = (props: Props) => {
    const [expanded, setExpanded] = React.useState(false);
    const contentEl = React.useRef(null);
    const style: React.CSSProperties = {};
    if (!expanded) {
        style.maxHeight = props.height || 100;
    } else {
        style.maxHeight = (contentEl.current && contentEl.current.clientHeight) || 10000;
    }

    return (
        <div style="{style}">
            <div>{props.children}</div>
            <a> setExpanded(!expanded)}&gt;
                <i>
            </i></a><i>
        </i></div><i>
    );
};</i>
github pinterest / gestalt / packages / gestalt / src / Checkbox.js View on Github external
export default function Checkbox({
  checked = false,
  disabled = false,
  hasError = false,
  id,
  indeterminate = false,
  name,
  onChange,
  onClick,
  size = 'md',
}: Props) {
  const inputElement = React.useRef(null);
  const [focused, setFocused] = React.useState(false);

  React.useEffect(() =&gt; {
    if (inputElement &amp;&amp; inputElement.current) {
      inputElement.current.indeterminate = indeterminate;
    }
  }, [indeterminate]);

  const handleChange = (event: SyntheticInputEvent&lt;&gt;) =&gt; {
    if (onChange) {
      onChange({ event, checked: event.target.checked });
    }
  };

  const handleClick = (event: SyntheticInputEvent) =&gt; {
    if (onClick) {