초기 state 재생성 방지하기
React는 초기 state를 한번 저장하고 다음 렌더링에서 이를 무시한다.
function createInitialState(username) {
// ...
}
function TodoList({ username }) {
const [state, dispatch] = useReducer(reducer, createInitialState(username));
// ...
createInitialState(username)의 결과는 초기 렌더링에만 사용되지만, 이후의 모든 렌더링에서도 여전히 이 함수를 호출한다. 이는 큰 배열을 만들거나 값비싼 계산을 수행하는 경우 낭비가 될 수 있다.
이 문제를 해결하려면 useReducer 세번째 인수에 초기화 함수를 전달할 수 있다.
function createInitialState(username) {
// ...
}
function TodoList({ username }) {
const [state, dispatch] = useReducer(reducer, username, createInitialState);
// ...
함수를 호출한 결과인 createInitialState()가 아니라 함수 자체인 createInitialState를 전달하고 있다는 점에 유의해야 한다. 이렇게 하면 초기화 한 후에는 초기 state가 다시 생성되지 않는다.
위의 예에서 createInitialState는 username 인수를 받는다. 초기화 함수가 초기 state를 계산하는데 아무런 정보가 필요하지 않은 경우, useReducer의 두번째 인수로 null을 전달할 수 있다.
아래 블로그에 설명이 잘 되어 있으니 참고 하자!
https://react.vlpt.us/basic/20-useReducer.html
20. useReducer 를 사용하여 상태 업데이트 로직 분리하기 · GitBook
20. useReducer 를 사용하여 상태 업데이트 로직 분리하기 이 프로젝트에서 사용된 코드는 다음 링크에서 확인 할 수 있습니다. useReducer 이해하기 우리가 이전에 만든 사용자 리스트 기능에서의 주
react.vlpt.us
import React, { useReducer, useState } from 'react';
function todoReducer(state, action) {
switch (action.type) {
case 'add':
return [...state, { id: Date.now(), text: action.text, completed: false }];
case 'toggle':
return state.map(todo =>
todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
);
case 'remove':
return state.filter(todo => todo.id !== action.id);
default:
throw new Error();
}
}
function TodoApp() {
const [todos, dispatch] = useReducer(todoReducer, []);
const [text, setText] = useState('');
const handleAddTodo = () => {
dispatch({ type: 'add', text });
setText('');
};
return (
<div>
<h1>Todo List</h1>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<button onClick={handleAddTodo}>Add Todo</button>
<ul>
{todos.map(todo => (
<li key={todo.id}>
<span
style={{
textDecoration: todo.completed ? 'line-through' : 'none'
}}
onClick={() => dispatch({ type: 'toggle', id: todo.id })}
>
{todo.text}
</span>
<button onClick={() => dispatch({ type: 'remove', id: todo.id })}>
Remove
</button>
</li>
))}
</ul>
</div>
);
}
export default TodoApp;
'React-study > dil' 카테고리의 다른 글
[DIL] useRef (0) | 2024.05.30 |
---|---|
[DIL] useContext (0) | 2024.05.29 |
[DIL] useReducer(1) (0) | 2024.05.27 |
[DIL] useState 사용법 (0) | 2024.05.20 |
[DIL] useState(2) (0) | 2024.05.17 |