후크는 2018 년 말 React 16.8에 도입되었습니다. 함수 컴포넌트에 연결되어 componentDidUpdate, componentDidMount 등과 같은 상태 및 컴포넌트 함수를 사용할 수 있는 함수입니다. 이전에는 불가능했습니다.
https://www.toptal.com/react/testing-react-hooks-tutorial
또한 후크를 사용하면 여러 구성 요소에서 구성 요소 및 상태 논리를 재사용 할 수 있습니다. 이것은 전에 까다로웠다. 따라서 후크는 게임 체인저였습니다.
import { useState, useEffect } from "react";
const CACHE = {};
export default function useStaleRefresh(url, defaultValue = []) {
const [data, setData] = useState(defaultValue);
const [isLoading, setLoading] = useState(true);
useEffect(() => {
// cacheID is how a cache is identified against a unique request
const cacheID = url;
// look in cache and set response if present
if (CACHE[cacheID] !== undefined) {
setData(CACHE[cacheID]);
setLoading(false);
} else {
// else make sure loading set to true
setLoading(true);
setData(defaultValue);
}
// fetch new data
fetch(url)
.then((res) => res.json())
.then((newData) => {
CACHE[cacheID] = newData;
setData(newData);
setLoading(false);
});
}, [url, defaultValue]);
return [data, isLoading];
}
등록된 댓글이 없습니다.