Custom hooks React Native

 Custom hooks React Native


Lần này TiT sẽ hướng dẫn m.n làm quen với custom hook và một vài ví dụ về custom hook-có thể bạn sẽ cần để m.n dễ hiểu hơn 💥💥💥

💜 Custom hook:

  • Là một function với output là dữ liệu chứ không phải là jsx như functional component.
  • Có tên theo quy tắc useXXX (XXX tuỳ vào feature của mn nha😙😙).
  • Có thể xử dụng các hook khác hoặc custom hook khác, khác so với 1 function thông thường.


💜 Ưu điểm:

  • Tách riêng logic với UI (Giao diện người dùng).
  • Tái sử dụng lại ở những component giống nhau về logic xử lý(Nhỡ có thay đổi gì thì thay đổi 1 chỗ là xong 😆 chứ không phải thay đổi nhiều chỗ 😅)
  • Ẩn các đoạn handle logic phức tạp của component => dễ đọc dễ hiểu hơn.


💜 Dùng khi nào👋😎

  • Khi 1 đoạn code logic được dùng chung ở nhiều nơi( khác mỗi tham số truyền vào còn cách xử lý y thế)
  • Logic xử lý dài và phức tạp, làm component bị nhiều rối mắt khi phải đọc luồng chạy của cả component😱😱.


💜 Dưới đây là 1 vài custom hook có thể mn sẽ cần nha 😊👇👇

💋 useDelayedInput

/* eslint-disable react-hooks/exhaustive-deps */
import {useEffect, useState} from 'react';

var timer: any = null;

export const useDelayedInput = (keyword: string = '', time: number = 500) => {
const [delayKeyword, setDelayKeyword] = useState(keyword);

useEffect(() => {
clearTimeout(timer);
timer = setTimeout(() => {
setDelayKeyword(keyword);

return () => {
clearTimeout(timer);
};
}, time);
}, [keyword]);

return {delayKeyword};
};

  • Mục đích💁: tạo ra để debounce input (phương pháp thực hiện tác vụ nào đó như call Api chả hạn sau 1 khoảng thời gian chờ sau khi nhập text vào ô input từ người dùng)
  • Output👉: từ khoá mà người dùng nhập vào nhưng mà đã bị delay ví dụ sau khoảng 500ms chả hạn nè
  • Sử dụng:
const [keyword, setKeyword] = useState('');
const {delayKeyword} = useDelayedInput(keyword, 2000);

useEffect(() => {
console.log(keyword);
}, [delayKeyword]);


💋 useAsync

import { useCallback, useEffect, useRef, useState } from "react";

export const useAsync = (
asyncFunction,
args = [],
deps = [],
immediate = true
) => {
const isFirstUpdate = useRef(true);

const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);

const execute = useCallback(() => {
setLoading(true);
setResponse(null);
setError(null);
return asyncFunction(...args)
.then((response) => {
setResponse(response);
})
.catch((error) => {
setError(error);
})
.finally(() => {
setLoading(false);
});
}, [asyncFunction, args]);

useEffect(() => {
if (immediate) {
execute();
} else {
if (!isFirstUpdate.current) {
execute();
}
}
}, [...deps]);

useEffect(() => {
    isFirstUpdate.current = false;
}, []);

return { execute, response, error, loading };
};
  • Mục đích💁: dùng để lấy dữ liêu, lỗi, ... khi gọi api.
  • Output👉: execute chỉ là export 1 function để call api thoii, dữ liệu, lỗi khi call api, tình trạng đang loading hay không. 
  • Khai báo, giải thích:

        💣 asyncFunction: là hàm gọi Api trả về 1 Promise, ví dụ như hàm để lấy 1 chuỗi có độ dài bất kì nè👀

export function getRandomQuoteApi(length) {
const url = `https://api.quotable.io/random?maxLength=${length}`;
return fetch(url).then((result) => result.json());
}

        💣 immediate là biến để xem khi chạy component này có call api lun không 
        💣 deps và args chắc mn cũng bít khi biết useCallback và useEffect rồi nhỏ 💪💪💪
  • Sử dụng:
const [maxLength, setMaxLength] = useState(30);
const getRandomQuote = useAsync(
getRandomQuoteApi,
[maxLength],
[maxLength],
true
);

Đó vậy là xong phần giới thiệu về custom hook và 1 số hook TiT hay dùng rồi đó. TiT sẽ cập nhập thêm các custom nếu có issue dùng tới nhó. Hy vọng mn cảm thấy bài này hữu ích và ủng hộ TiT <3 




Đăng nhận xét

Mới hơn Cũ hơn