DEV Community

Cover image for Top 10 most useful react hooks.
NisalK
NisalK

Posted on • Edited on

Top 10 most useful react hooks.

What is this article about?
React Hooks are a new feature in React that allows you to use state and other React features in functional components instead of just class-based components. Before the introduction of hooks, functional components were only able to receive props and render the components.

Hooks provide a way to use state and other React features in functional components by allowing you to "hook into" React's features. React provides a few built-in hooks like useState, useEffect, useContext and useReducer that can be used to add state and other functionality to functional components.

In this article we are going to discuss about 10 custom hooks from Mantine.dev components library. Matine Hooks is a library for React that provides additional hooks for common functionality such as managing state, handling lifecycle events, and interacting with external APIs. It is an open-source project that aims to make it easier for developers to build complex and dynamic user interfaces using React.

01 useIdle

Detect if user is idle or active on page
useIdle hook demo

import { useIdle } from '@mantine/hooks';
import { Badge } from '@mantine/core'; // optiona
function Demo() {
  const idle = useIdle(2000);
  return <Badge color={idle ? 'blue' : 'teal'}>Current state: {idle ? 'idle' : 'not idle'}</Badge>;
}
Enter fullscreen mode Exit fullscreen mode

02 useClickOutside

Detect click and touch events outside of specified element , useful to close opened modals components
use click outside hook demo

import { useState } from 'react';
import { Paper, Button } from '@mantine/core';
import { useClickOutside } from '@mantine/hooks';

function Demo() {
  const [opened, setOpened] = useState(false);
  const ref = useClickOutside(() => setOpened(false));

  return (
    <>
      <Button onClick={() => setOpened(true)}>Open dropdown</Button>

      {opened && (
        <Paper ref={ref} shadow="sm">
          <span>Click outside to close</span>
        </Paper>
      )}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

03 useOs

Detect user's operating system
useOS demo image

import { useOs } from '@mantine/hooks';

function Demo() {
  const os = useOs();
  return <>Your os is <b>{os}</b></>;
}
Enter fullscreen mode Exit fullscreen mode

04 useNetwork

Get current connection status

use network hook demo image

import { Text, Table } from '@mantine/core';
import { useNetwork } from '@mantine/hooks';

function Demo() {
  const networkStatus = useNetwork();

  return (
    <Table sx={{ maxWidth: 300, tableLayout: 'fixed' }} mx="auto">
      <thead>
        <tr>
          <th>Property</th>
          <th>Value</th>
        </tr>
      </thead>

      <tbody>
        <tr>
          <td>Online</td>
          <td>
            <Text size="sm" color={networkStatus.online ? 'teal' : 'red'}>
              {networkStatus.online ? 'Online' : 'Offline'}
            </Text>
          </td>
        </tr>

        <tr>
          <td>rtt</td>
          <td>{networkStatus.rtt}</td>
        </tr>

        <tr>
          <td>downlink</td>
          <td>{networkStatus.downlink}</td>
        </tr>

        <tr>
          <td>effectiveType</td>
          <td>{networkStatus.effectiveType}</td>
        </tr>

        <tr>
          <td>saveData</td>
          <td>
            <Text size="sm" color={networkStatus.saveData ? 'teal' : 'red'}>
              {networkStatus.saveData ? 'true' : 'false'}
            </Text>
          </td>
        </tr>
      </tbody>
    </Table>
  );
}
Enter fullscreen mode Exit fullscreen mode

05 useEyeDropper

Pick color from any pixel on the screen
use eye dropper hook demo image

import { useState } from 'react';
import { ActionIcon, Group, ColorSwatch, Text } from '@mantine/core';
import { IconColorPicker } from '@tabler/icons';
import { useEyeDropper } from '@mantine/hooks';

function Demo() {
  const [color, setColor] = useState('');
  const [error, setError] = useState(null);
  const { supported, open } = useEyeDropper();

  const pickColor = async () => {
    try {
      const { sRGBHex } = await open();
      setColor(sRGBHex);
    } catch (e) {
      setError(e);
    }
  };

  if (!supported) {
    return <Text ta="center">EyeDropper API is not supported in your browser</Text>;
  }

  return (
    <Group>
      <ActionIcon variant="default" onClick={pickColor}>
        <IconColorPicker size={16} stroke={1.5} />
      </ActionIcon>
      {color ? (
        <Group spacing="xs">
          <ColorSwatch color={color} />
          <Text>Picked color: {color}</Text>
        </Group>
      ) : (
        <Text>Click the button to pick color</Text>
      )}
      {error && <Text color="red">Error: {error?.message}</Text>}
    </Group>
  );
}
Enter fullscreen mode Exit fullscreen mode

06 useWindowScroll

Subscribe to window scroll and scroll smoothly to given position
use window scroll hook demo image

import { useWindowScroll } from '@mantine/hooks';
import { Button, Text, Group } from '@mantine/core';

function Demo() {
  const [scroll, scrollTo] = useWindowScroll();

  return (
    <Group position="center">
      <Text>
        Scroll position x: {scroll.x}, y: {scroll.y}
      </Text>
      <Button onClick={() => scrollTo({ y: 0 })}>Scroll to top</Button>
    </Group>
  );
}
Enter fullscreen mode Exit fullscreen mode

07 useToggle

Switch between given values
use toggle hook demo image

import { Button } from '@mantine/core';
import { useToggle } from '@mantine/hooks';

function Demo() {
  const [value, toggle] = useToggle(['blue', 'orange', 'cyan', 'teal']);

  return (
    <Button color={value} onClick={() => toggle()}>
      {value}
    </Button>
  );
}
Enter fullscreen mode Exit fullscreen mode

08 useLocalStorage

Use localStorage value as react state, sync state across opened tabs

import { useLocalStorage } from '@mantine/hooks';
import { ActionIcon, ColorScheme } from '@mantine/core';
import { IconSun, IconMoonStars } from '@tabler/icons';

function ColorSchemeToggle() {
  const [colorScheme, setColorScheme] = useLocalStorage<ColorScheme>({
    key: 'color-scheme',
    defaultValue: 'light',
  });

  const toggleColorScheme = () =>
    setColorScheme((current) => (current === 'dark' ? 'light' : 'dark'));

  return (
    <ActionIcon onClick={toggleColorScheme}>
      {colorScheme === 'dark' ? <IconSun /> : <IconMoonStars />}
    </ActionIcon>
  );
}
Enter fullscreen mode Exit fullscreen mode

09 useMediaQuery

Subscribe to media queries with window.matchMedia
use media query demo image

import { Badge } from '@mantine/core';
import { useMediaQuery } from '@mantine/hooks';

function Demo() {
  const matches = useMediaQuery('(min-width: 900px)');

  return (
    <Badge color={matches ? 'teal' : 'red'} variant="filled">
      Breakpoint {matches ? 'matches' : 'does not match'}
    </Badge>
  );
}
Enter fullscreen mode Exit fullscreen mode

10 useFullscreen

Enter/exit fullscreen with given element
use full screen hook demo image

import { useFullscreen } from '@mantine/hooks';
import { Button } from '@mantine/core';

function Demo() {
  const { toggle, fullscreen } = useFullscreen();

  return (
    <Button onClick={toggle} color={fullscreen ? 'red' : 'blue'}>
      {fullscreen ? 'Exit Fullscreen' : 'Enter Fullscreen'}
    </Button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Need more?
There are more than 40+ hooks are available.
Checkout here 👉 https://mantine.dev/hooks/use-counter/
I hope this article has been useful to you , Follow me 😊

Top comments (0)