보통 컴포넌트를 만들 때 아무 생각 없이 렌더링하는 부분과 데이터를 받아오는 함수를 같이 두었다.
하지만 이 둘을 분리시켜 주면서 코드의 흐름을 더 빠르게 파악할 수 있고, 로직상 분리를 통해 역할 분담을 더 깰-꼼하게 할 수 있다는 것!
< 기존 코드 >
많은 코드가 아니라 그리 복잡해 보이지 않지만 데이터를 더 많이 가져올수록 코드는 더 길어지게된다.
import React, { useState, useEffect } from "react";
import TodayDate from "./TodayDate/TodayDate";
import InputBox from "./InputBox/InputBox";
import Content from "./Content/Content";
import { ITodo } from "../type/Todo";
function TodoList() {
const [todoList, setTodoList] = useState<ITodo[]>(
JSON.parse(localStorage.getItem("todolist") ?? "[]"), // 검색
);
const [leftCount, setLeftCount] = useState<number>(0);
useEffect(() => {
localStorage.setItem("todolist", JSON.stringify(todoList));
const leftTodoCount = todoList.filter(todo => !todo.done).length;
setLeftCount(leftTodoCount);
}, [todoList]);
return (
<div className="main">
<TodayDate />
<div className="right-side">
<Content
leftCount={leftCount}
todoList={todoList}
setTodoList={setTodoList}
/>
<InputBox setTodoList={setTodoList} />
</div>
</div>
);
}
export default TodoList;
<변경된 코드>
import TodayDate from "./TodayDate/TodayDate";
import InputBox from "./InputBox/InputBox";
import Content from "./Content/Content";
import useTodo from "../hooks/useTodo";
function TodoList() {
const [todoList, setTodoList] = useTodo();
return (
<div className="main">
<TodayDate />
<div className="right-side">
<Content
leftCount={todoList.length}
todoList={todoList}
setTodoList={setTodoList}
/>
<InputBox setTodoList={setTodoList} />
</div>
</div>
);
}
export default TodoList;
useTodo라는 custom hook을 만들어서
// todo 데이터를 관리하는 역할을 하는 훅
import { useState, useEffect } from "react";
import { TodoType } from "../type/Todo";
function useTodo(): [
TodoType[],
React.Dispatch<React.SetStateAction<TodoType[]>>,
] {
const [todoList, setTodoList] = useState<TodoType[]>([]);
// const [leftCount, setLeftCount] = useState<number>(0);
useEffect(() => {
// localStorage.setItem("todolist", JSON.stringify(todoList));
// const leftTodoCount = todoList.filter(todo => !todo.done).length;
// setLeftCount(leftTodoCount);
fetch("http://localhost:8000/todos")
.then(x => x.json())
.then(todos => setTodoList(todos));
}, []);
return [todoList, setTodoList];
}
export default useTodo;
이렇게 데이터를 받아오는 로직을 분리시켜 주고
렌더링하는 컴포넌트에서 훅을 통해 데이터를 가져온다.
'React' 카테고리의 다른 글
[에러 해결]Cannot add property, object is not extensible (0) | 2023.08.28 |
---|---|
state 지연 초기화 (0) | 2023.08.01 |
반복문을 객체 혹은 배열로 변경해보기 (0) | 2023.08.01 |
lazy&suspense (0) | 2023.07.17 |
[React]SPA와 라우팅 (0) | 2022.11.23 |