Bản chất của một hook là một hàm. Do đó, ta hoàn toàn có thể tự tạo ra hook của riêng mình.
useFetch
Giả sử chúng ta cần một hook chịu trách nhiệm lấy dữ liệu từ API, ta sẽ tạo ra một hook có tên là useFetch
. Việc đặt tên với tiền tố use
giúp cho React nhận biết đây là một hook.
Trước tiên ta tạo hàm với state mặc định như sau:
import { useState } from 'react'
function useFetch(url) {
const [data, setData] = useState([])
return data
}
export default useFetch
Hook này cần nhận một tham số đầu vào là url
, cho biết API nào sẽ được gọi.
Chúng ta sử dụng useEffect
để xử lý việc gọi API.
import { useState, useEffect } from 'react'
import axios from 'axios'
function useFetch(url) {
const [data, setData] = useState([])
useEffect(() => {
async function fetchData() {
try {
const response = await axios.get(url)
if(!ignore) {
setData(response.data)
console.log(data)
}
} catch(error) {
console.error(error.message)
}
}
fetchData()
}, [url])
return data
}
export default useFetch
Gọi sử dụng như sau:
import useFetch from './hooks/useFetch'
function App() {
const data = useFetch('https://nekos.best/api/v2/neko?amount=20')
return (
<>
{data.results ? (
data.results.map((neko, index) => {
return <img src={neko.url} alt={`Neko ${index}`} />
})
) : (
<p>Loading...</p>
)}
</>
)
}
export default App
Lần đầu gọi API, state của useFetch
có thể chưa có dữ liệu. Khi đó, giá trị trả về của useFetch
sẽ là []
.
useToggle
import { useState } from 'react'
function useToggle(defaultValue) {
const [value, setValue] = useState(defaultValue)
function toggleValue(value) {
setValue(currentValue =>
typeof value === "boolean" ? value : !currentValue
)
}
return [value, toggleValue]
}
export default useToggle
Ví dụ sử dụng:
import useToggle from "./hooks/useToggle";
function ToggleComponent() {
const [value, toggleValue] = useToggle(false);
return (
<div>
<div>{value.toString()}</div>
<button onClick={toggleValue}>Toggle</button>
<button onClick={() => toggleValue(true)}>Make True</button>
<button onClick={() => toggleValue(false)}>Make False</button>
</div>
);
}
export default ToggleComponent
Related
list
from [[Custom Hook]]
sort file.ctime asc