728x90
What are "Custom Hooks"?
- Outsource stateful logic into re-usable functions
- Unlike "regular functions", custom hooks can use other React hooks and React state
- The name must start with 'use'
Sample Code
src/hooks/use-http.js
import { useState, useCallback } from 'react';
const useHttp = () => {
const [isLoading, setIsLoading] useState(false);
const [error, setError] useState(null);
const sendRequest = useCallback(async (requestConfig, applyData) => {
setIsLoading(true);
setError(null);
try {
const response = await fetch(
requestConfig.url, {
method: requestConfig.method,
headers: requestConfig.headers,
body: JSON.stringify(requestConfig.body)
}
);
if (!response.ok) {
throw new Error('Request failed!');
}
const data = await response.json();
applyData(data);
} catch (err) {
setError(err.message || 'Something went wrong');
}
setIsLoading(false);
}, []);
return {
isLoading: isLoading,
error: error,
sendRequest: sendRequest
}
};
export default useHttp;
src/components/FowardCounter.js
import { useState, useEffect, useCallback } from 'react';
import useHttp from '../hooks/use-http';
const App = () => {
const [tasks, setTasks] = useState([]);
const { isLoading, error, sendRequest: fetchTasks } = useHttp();
useEffect(() => {
const transformTasks = (tasksObj) => {
const loadedTasks = [];
for (const taskKey in tasksObj) {
loadedTasks.push({ id: taskKey, text: tasksObj[taskKey].text });
}
setTasks(loadedTasks);
};
fetchTasks({ method: 'GET', url: 'https://...', body: null }, transformTasks);
}, [fetchTasks]);
const taskAddHandler = (task) => {
setTasks((prevTasks) => prevTasks.concat(task));
};
return (
<React.Fragment>
<Tasks
items={tasks}
loading={isLoading}
error={error}
onFetch={fetchTasks}
/>
</React.Fragment>
);
};
728x90
'Study Note > React' 카테고리의 다른 글
Next.js #Image src - External CDN image is not visible (0) | 2022.10.06 |
---|---|
React #Redux (0) | 2022.09.24 |
React #Rules of Hooks (0) | 2022.09.24 |
React #Understanding useReducer() (0) | 2022.09.24 |
React #mongoose #페이지네이션 구현 (0) | 2021.03.17 |
댓글