useState
, useEffect
, useReducer
, useCallback
, useMemo
λ± μ¬λ¬ λ΄μ₯ ν¨μ μ‘΄μ¬μ½λ μΆμν : νλ‘κ·Έλλ°μμ νΉμ ν κΈ°λ₯, λμ λλ κ°λ
μ μΌλ°ννκ±°λ λ¨μννμ¬ μ¬μ©μκ° λ μ½κ² μ΄ν΄νκ³ νμ©ν μ μλλ‘ νλ κ³Όμ
use-
λ‘ μμuseFetchData.jsx
import { useState, useEffect } from 'react';
function useFetchData(url) {
// 컀μ€ν
ν
μμμ μ¬μ¬μ©ν λ΄λΆ μν κ°μ Έμ΄
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => {
setData(data);
})
.catch((error) => {
setError(error);
})
.finally(() => {
setLoading(false);
});
}, [url]);
// μΈλΆμ 곡μ νκ³ μΆμ λ°μ΄ν° return
return { data, loading, error };
}
export default useFetchData;
μ¬μ©νλ νμΌ.jsx
import React from 'react';
// 컀μ€ν
ν
import
import useFetchData from './useFetchData';
function App() {
// 컀μ€ν
ν
μ¬μ©
const { data, loading, error } = useFetchData('https://example.url');
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return (
<div>
<h1>Post Title: {data?.title}</h1>
<p>Post Body: {data?.body}</p>
</div>
);
}
export default App;
useFetchData.jsx
컀μ€ν
ν
μ νμ©ν΄ λ κ°κ²°νκ² λ°μμ¬ μ μμ
μ μ΅ν κΈμ΄μμ΅λλ€.