function handleAddTask(text) {
setTasks([
...tasks,
{
id: nextId++,
text: text,
done: false,
},
]);
}
function handleChangeTask(task) {
setTasks(
tasks.map((t) => {
if (t.id === task.id) {
return task;
} else {
return t;
}
})
);
}
function handleDeleteTask(taskId) {
setTasks(tasks.filter((t) => t.id !== taskId));
}
위 코드의 모든 setTask를 제거. 남는 것은,
대신에, 방금 유저가 한 action을 전달한다.
function handleAddTask(text) {
dispatch({
type: 'added',
id: nextId++,
text: text,
});
}
function handleChangeTask(task) {
dispatch({
type: 'changed',
task: task,
});
}
function handleDeleteTask(taskId) {
dispatch({
type: 'deleted',
id: taskId,
});
}
function tasksReducer(tasks, action) {
switch (action.type) {
case 'added': {
return [
...tasks,
{
id: action.id,
text: action.text,
done: false,
},
];
}
case 'changed': {
return tasks.map((t) => {
if (t.id === action.task.id) {
return action.task;
} else {
return t;
}
});
}
case 'deleted': {
return tasks.filter((t) => t.id !== action.id);
}
default: {
throw Error('Unknown action: ' + action.type);
}
}
}
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
부모의 state를 바로 아래 자식이 아니라, 저~멀리 떨어진 자식에게 필요한 경우?
export const LevelContext = createContext(1);
const level = useContext(LevelContext);
export default function Section({ level, children }) {
return (
<section className="section">
<LevelContext.Provider value={level}>
{children}
</LevelContext.Provider>
</section>
);
}
div color:blue
처럼, 중간에 어디선가 color:green
하지 않는 이상 색깔은 하위 요소로 상속되는 것과 비슷함.function Layout({ posts }) {
return (
<div>
<Header />
<Main posts={posts} />
</div>
);
}
function Main({ posts }) {
return (
<div>
<Posts posts={posts} />
</div>
);
}
위 코드는 Posts component에서 쓸 posts를 props로 내리전달하고 있음.
function Layout({ children }) {
return (
<div>
<Header />
{children}
</div>
);
}
function Main({ children }) {
return (
<div>
{children}
</div>
);
}
이렇게 children을 사용하고,
<Layout>
<Main>
<Posts posts={somePostsData} />
</Main>
</Layout>
이렇게 전달.
이 방법들이 잘 적용되지 않을 때, context 사용을 고려하자.
https://react.dev/learn/extracting-state-logic-into-a-reducer
https://react.dev/learn/passing-data-deeply-with-context