Top 10 most useful react hooks.
Tags: react, javascript, tutorial, beginners
Published: 2023-01-17 18:48:05

**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](https://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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bgid9cx3qizo5t080p24.gif)

```react
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>;
}
```
## 02 useClickOutside
_Detect click and touch events outside of specified element , useful to close opened modals components_
![use click outside hook demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ljnkxgsqf8teho169dh.gif)
```react
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>
      )}
    </>
  );
}
```
## 03 useOs
_Detect user's operating system_
![useOS demo image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nz98t8xl40wn6so6dyb2.png)
```react
import { useOs } from '@mantine/hooks';

function Demo() {
  const os = useOs();
  return <>Your os is <b>{os}</b></>;
}
```
## 04 useNetwork
_Get current connection status_

![use network hook demo image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/84jljnie7vdayjwttvlt.png)
```react
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>
  );
}
```

## 05 useEyeDropper
_Pick color from any pixel on the screen_
![use eye dropper hook demo image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zqqsqx4gb5w0234foitj.gif)
```react
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>
  );
}
```
## 06 useWindowScroll
_Subscribe to window scroll and scroll smoothly to given position_
![use window scroll hook demo image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5pjoqao85yqbastmxw49.png)
```react
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>
  );
}
```
## 07 useToggle
_Switch between given values_
![use toggle hook demo image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/476ilxrbq9de9i8drg6n.gif)

```react
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>
  );
}
```
## 08 useLocalStorage
_Use localStorage value as react state, sync state across opened tabs_
```react
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>
  );
}
```
## 09 useMediaQuery
_Subscribe to media queries with window.matchMedia_
![use media query demo image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ig4rdhsp9qt45omzsdg3.gif)
```react
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>
  );
}
```
## 10 useFullscreen
_Enter/exit fullscreen with given element_
![use full screen hook demo image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sw16fby118gxvwfc19xl.png)
```react
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>
  );
}
```
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 😊**