30 seconds of React

Hooks

Click on a snippet's name to view its code.

useClickInside

A hook that handles the event of clicking inside the wrapped component.

  • Create a custom hook that takes a ref and a callback to handle the click event.
  • Use the React.useEffect() hook to append and clean up the click event.
  • Use the React.useRef() hook to create a ref for your click component and pass it to the useClickInside hook.

useClickOutside

A hook that handles the event of clicking outside of the wrapped component.

  • Create a custom hook that takes a ref and a callback to handle the click event.
  • Use the React.useEffect() hook to append and clean up the click event.
  • Use the React.useRef() hook to create a ref for your click component and pass it to the useClickOutside hook.

useFetch

A hook that implements fetch in a declarative manner.

  • Create a custom hook that takes a url and options.
  • Use the React.useState() hook to initialize the response and error state variables.
  • Use the React.useEffect() hook to anychronously call fetch() and update the state varaibles accordingly.
  • Return an object containting the response and error state variables.

useInterval

A hook that implements setInterval in a declarative manner.

  • Create a custom hook that takes a callback and a delay.
  • Use the React.useRef() hook to create a ref for the callback function.
  • Use the React.useEffect() hook to remember the latest callback.
  • Use the React.useEffect() hook to set up the interval and clean up.

useNavigatorOnLine

A hook that returns if the client is online or offline.

  • Create a function, getOnLineStatus, that uses the NavigatorOnLine web API to get the online status of the client.
  • Use the React.useState() hook to create an appropriate state variable, status, and setter.
  • Use the React.useEffect() hook to add listeners for appropriate events, updating state, and cleanup those listeners when unmounting.
  • Finally return the status state variable.

useSSR

A hook that checks if the code is running on the browser or the server.

  • Create a custom hook that returns an appropriate object.
  • Use typeof window, window.document and window.document.createElement to check if the code is running on the browser.
  • Use the React.useState() hook to define the inBrowser state variable.
  • Use the React.useEffect() hook to update the inBrowser state variable and clean up at the end.
  • Use the React.useMemo() to memoize the return values of the custom hook.

useTimeout

A hook that implements setTimeout in a declarative manner.

  • Create a custom hook that takes a callback and a delay.
  • Use the React.useRef() hook to create a ref for the callback function.
  • Use the React.useEffect() hook to remember the latest callback.
  • Use the React.useEffect() hook to set up the timeout and clean up.