- vừa được xem lúc

Blog#120: 🌸7 React Hooks You Need to Know About🌸

0 0 31

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.


Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

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.

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.

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.

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.

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.

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.

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.

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.

And Finally

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊


The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 528

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 436

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 158

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 149

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 113

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 249