Trung BìnhReact iconReact

Custom hooks là gì? Viết custom hook useFetch đơn giản?

Custom hooks là functions bắt đầu bằng use, tái sử dụng logic stateful giữa components.

js
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    fetch(url)
      .then(r => r.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [url]);
  return { data, loading, error };
}

Xem toàn bộ React cùng filter theo level & chủ đề con.

Mở danh sách React