: κ°λ°μκ° μ€μ€λ‘ 컀μ€ν
ν Hook
Custom Hookμ λ§λ€λ©΄ λ°λ³΅λλ λ‘μ§μ ν¨μλ‘ λ½μλ΄μ΄ μ¬μ¬μ©ν μ μλ€.
μν κ΄λ¦¬ λ‘μ§μ μ¬νμ©μ΄ κ°λ₯νλ€.
ν΄λμ€ μ»΄ν¬λνΈλ³΄λ€ μ μ μμ μ½λλ‘ λμΌν λ‘μ§μ ꡬνν μ μλ€.
ν¨μν(useSomething()
)μΌλ‘ μμ±νκΈ° λλ¬Έμ, 보기μ λͺ
λ£νλ€.
Custom Hook λ΄λΆμμ React λ΄μ₯ Hookμ μ¬μ©ν μλ μλ€.
μΌλ° ν¨μ λ΄λΆμμλ React Hookμ λΆλ¬ μ¬μ©ν μ μμ§λ§, Custom Hook λ΄λΆμμλ κ°λ₯νλ€.
Custom Hookμ μ¬μ©νλ μ»΄ν¬λνΈλ€μ μ»΄ν¬λνΈλ§λ€ stateμ effectλ₯Ό λ
립μ μΌλ‘ κ°μ§λ€. (μ¬μ¬μ©μ± β)
κ°μ Custom Hookμ μ¬μ©νλ€κ³ ν΄μ λ μ»΄ν¬λνΈκ° κ°μ stateλ₯Ό 곡μ νλ κ²μ΄ μλλ€.
κ·Έμ λ‘μ§λ§ 곡μ ν λΏ, stateλ κ° μ»΄ν¬λνΈ λ΄μμ λ
립μ μΌλ‘ μ μλλ€.
use
λ₯Ό λΆμΈλ€.: fetch APIλ₯Ό ν΅ν΄ λ€νΈμν¬μμμ λ°μ΄ν°λ₯Ό κ°μ Έμ¬ μ μκ² ν΄μ£Όλ Custom Hook
import useFetch from './hooks/useFetch';
function App() {
const url = "https://jsonplaceholder.typicode.com/users";
const fetchedData = useFetch(url);
console.log(fetchedData); // λ°μ΄ν°λ₯Ό λ°μμ€λ κ²μ νμΈν μ μλ€.
return (
<div></div>
);
}
export default App;
import { useEffect, useState } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
const fetchUrl = () => {
fetch(url)
.then((res) => res.json())
.then((data) => setData(data));
}
useEffect(() => {
fetchUrl(url); // fetchUrl ν¨μ νΈμΆ
}, [url]); // urlμ΄ λ³κ²½λ λλ§λ€ μ€νλλ€.
return data;
}
export default useFetch;
μ¬λ¬ κ°μ inputμ μν μν λ³κ²½μ ν λ μΈ μ μλ Custom Hook
import useInput from './hooks/useInput';
const displayMessage = (message) => {
alert(message);
};
function App() {
const [inputValue, handleChange, handleSubmit] = useInput('', displayMessage);
return (
<div>
<input value={inputValue} onChange={handleChange} />
<button onClick={handleSubmit}>νμΈ</button>
</div>
);
}
export default App;
import { useState } from "react";
const useInput = (initialValue, submitAction) => {
const [inputValue, setInputValue] = useState(initialValue);
const handleChange = (e) => {
setInputValue(e.target.value);
};
const handleSubmit = () => {
setInputValue('');
submitAction(inputValue);
};
return [inputValue, handleChange, handleSubmit];
}
export default useInput;