const count = useMemo(() => countActiveUsers(users), [users]);
return (
<>
<CreateUser
username={username}
email={email}
onChange={onChange}
onCreate={onCreate}
/>
<UserList users={users} onRemove={onRemove} onToggle={onToggle} />
<div>활성사용자 수 : {count}</div>
</>
);
}
export default App;
const onRemove = id => {
setUsers(users.filter(user => user.id !== id));
};
// 위 코드를 아래와 같이 변경
const onRemove = useCallback(
id => {
setUsers(users.filter(user => user.id !== id));
},
[users]
);
import React from 'react';
const CreateUser = ({ username, email, onChange, onCreate }) => {
return (
<div>
<input
name="username"
placeholder="계정명"
onChange={onChange}
value={username}
/>
<input
name="email"
placeholder="이메일"
onChange={onChange}
value={email}
/>
<button onClick={onCreate}>등록</button>
</div>
);
};
export default React.memo(CreateUser); // 이와 같이 작성
Tip
function reducer(state, action) {
// 새로운 상태를 만드는 로직
// const nextState = ...
return nextState;
}
function Counter() {
const [number, dispatch] = useReducer(reducer, 0);
}
// 사용 예시
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
function Counter() {
const [number, dispatch] = useReducer(reducer, 0);
const onIncrease = () => {
dispatch({ type: 'INCREMENT' });
};
const onDecrease = () => {
dispatch({ type: 'DECREMENT' });
};
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
);
}
// 새 할 일을 등록하는 액션
{
type: 'ADD_TODO',
todo: {
id: 1,
text: 'useReducer 배우기',
done: false,
}
}
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'INCREMENT' })
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
const [value, setValue] = useState(true);
setUsers(users => users.concat(user));
setInputs({
username: '',
email: ''
});
function UserList({ users, onRemove, onToggle }) {
return (
<div>
{users.map(user => (
<User
user={user}
key={user.id}
onRemove={onRemove}
onToggle={onToggle}
/>
))}
</div>
);
}
const UserDispatch = React.createContext(null); // 선언 및 기본값 설정
import { UserDispatch } from './App'; // 나중에 이렇게 불러와서 사용 가능
// UserDispatch 라는 이름으로 내보내줍니다.
export const UserDispatch = React.createContext(null);
// Provider를 이용해 값 설정
<UserDispatch.Provider value={dispatch}>...</UserDispatch.Provider>