+10

🌸7 React Hooks You Need to Know About🌸

React Hooks are special features that make it easier to reuse code in your React projects. There are seven important React Hooks that you can use in every project. These Hooks come from a library called @mantine/hooks, which has lots of helpful features for your React app.

The useIntersection Hook

When you use an app, sometimes you scroll down the page. The app might want to know when you can see certain things on the page. For example, the app might want to start an animation when you can see a certain thing. Or, the app might want to show or hide something after you have scrolled down the page a certain amount.

0_ovJtOOaaf3U_cs7m.gif

We can use the Intersection Observer API to find out if something is visible on the screen. It's a special type of JavaScript that is built into the web browser. We can use it on its own, or use the useIntersection hook to get information about if a certain element is in the area that we can see when we scroll.

import { useRef } from 'react';
import { useIntersection } from '@mantine/hooks';

function Demo() {
  const containerRef = useRef();
  const { ref, entry } = useIntersection({
    root: containerRef.current,
    threshold: 1,
  });
  return (
    <main ref={containerRef} style={{ overflowY: 'scroll', height: 300 }}>
      <div ref={ref}>
        <span>
          {entry?.isIntersecting ? 'Fully visible' : 'Obscured'}
        </span>
      </div>
    </main>
  );
}

We can use a special hook to keep track of when an element is visible or not in a scroll container. We need to give the hook a reference to the scroll container and the element we want to track. Then, it will tell us when the element is visible or not. We can also adjust how much of the element needs to be visible for it to count as visible.

The useScrollLock Hook

This hook helps you when you want to show something on the screen that you don't want people to scroll away from. It stops people from scrolling up and down on the page, so that all the attention is on the thing you want them to look at. It also lets you have a special area that you can scroll in, so you can still move around the page.

import { useScrollLock } from '@mantine/hooks';
import { Button, Group } from '@mantine/core';
import { IconLock, IconLockOpen } from '@tabler/icons';

function Demo() {
  const [scrollLocked, setScrollLocked] = useScrollLock();
  return (
    <Group position="center">
      <Button
        onClick={() => setScrollLocked((c) => !c)}
        variant="outline"
        leftIcon={scrollLocked ? <IconLock size={16} /> : <IconLockOpen size={16} />}
      >
        {scrollLocked ? 'Unlock scroll' : 'Lock scroll'}
      </Button>
    </Group>
  );
}

useScrollLock is a way to keep your place on a page. It will tell you if the scroll is locked or not, and you can use it to show different content when the scroll is locked. For example, you can use it to show a message that the scroll is locked.

0_RyT3uf-gAhxnjURy.gif

The useClipboard Hook

You can make it easier for people to copy something from your website by using the Clipboard API. The useClipboard hook gives you a copy function that you can use to copy a code snippet or other text. This way, people can easily copy the text and paste it wherever they want.

0_VM8Aef0vDgrq2s8H.gif

When you press the copy button, we make a copy of the code snippet and show you a checkmark to let you know it was copied. The copy button also has a timer that will reset after a certain amount of time so you can copy the text again.

The useDebouncedValue Hook

If you have a search box in your app, useDebouncedValue is a helpful tool. It stops your app from sending too many requests when someone is typing in the search box. Instead, it waits until the person has finished typing before sending the request. This helps make sure that your app isn't sending too many requests and makes sure the search results are more accurate.

import { useState } from 'react';
import { useDebouncedValue } from '@mantine/hooks';
import { getResults } from 'api';

function Demo() {
  const [value, setValue] = useState('');
  const [results, setResults] = useState([])
  const [debounced] = useDebouncedValue(value, 200); // wait time of 200 ms
    
  useEffect(() => {
    if (debounced) {
      handleGetResults() 
    }
     
    async function handleGetResults() {
       const results = await getResults(debounced)   
       setResults(results)
    }
  }, [debounced])
  return (
    <>
      <input
        label="Enter search query"
        value={value}
        style={{ flex: 1 }}
        onChange={(event) => setValue(event.currentTarget.value)}
      />
      <ul>{results.map(result => <li>{result}</li>}</ul>
    </>
  );
}

You can save the words you type into a special place called state. You can also tell the special place to wait a certain amount of time before it sends the words you typed. This way, you don't have to send the words you typed too often. You can see this in the video where the words you type don't appear until after 200 milliseconds.

0_h2ERrCEnyadP2Bkk.gif

The useMediaQuery Hook

The useMediaQuery hook helps us to change the look of something depending on the size of the screen. For example, if the screen is 900 pixels wide, we can use the hook to make something look different. The hook will tell us if the screen size matches what we asked for and then we can change the look of something.

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

function Demo() {
  const matches = useMediaQuery('(min-width: 900px)');
  return (
    <div style={{ color: matches ? 'teal' : 'red' }}>
      {matches ? 'I am teal' : 'I am red'}
    </div>
  );
}

This means that we can use JavaScript to change the way something looks, like the color or size. We can do this by using the style property.

0_7pHrwX5tMZ04YtWw.gif

In some cases, when you can't use CSS to make something look different on different devices, this thing can help.

The useClickOutside Hook

This hook helps us make sure that when someone clicks outside of a certain element, like a pop-up, it will close. It's like a way to make sure that when someone clicks outside of the pop-up, it will close automatically.

import { useState } from 'react';
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 && (
        <div ref={ref} shadow="sm">
          <span>Click outside to close</span>
        </div>
      )}
    </>
  );
}

When you click outside of a certain element, useClickOutside will run a special function that tells the computer what to do. Usually, this function will make the element close. To do this, you need to give the computer a command (like setOpened) that tells it to make the element close.

0_XlbDwxfqaG6rfVqH.gif

The useForm Hook

My favorite hook helps me create forms in React. It's called useForm and it comes from Mantine. I need to install a package from the library called @mantine/form to use it. It helps me make sure the information I put in the form is correct before I submit it. It also helps me validate inputs and show error messages. I can give it some initial values to match the inputs in my form.

import { TextInput, Button } from '@mantine/core';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: {
      email: ''
    },
    validate: {
      email: (value) => (/^\S+@\S+$/.test(value) ? null : 'Invalid email'),
    },
  });
  return (
    <div>
      <form onSubmit={form.onSubmit((values) => console.log(values))}>
        <TextInput
          withAsterisk
          label="Email"
          placeholder="your@email.com"
          {...form.getInputProps('email')}
        />
        <Button type="submit">Submit</Button>
      </form>
    </div>
  );
}

useForm has a special feature called the validate function. It looks at what you type into each box on the form and checks if it is correct. For example, if you type in an email address, the validate function will make sure it is a real email address. If it isn't, it will show an error message and won't let you submit the form.

0_qUzSum0apXSrv6au.gif

If you're filling out a form, useForm is a tool that can help you keep track of the values you type in and make sure that the form is filled out correctly. It will also help you prevent submitting the form if it doesn't meet the rules. It makes it easier to fill out forms and make sure everything is done correctly.

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí