- 함수의 값을 재사용한다.
- 주로 성능을 최적화 할때 사용한다.
import React, { useRef, useState, useMemo } from 'react';
import UserList from './UserList';
import CreateUser from './CreateUser';
function CountAtivedUsers(users){
console.log('활성 사용자 수를 세는중..')
return users.filter(user => user.active).length;
}
function App() {
const [inputs, setInputs] = useState(
{
username: '',
email: 's'
}
);
const { username, email } = inputs;
const onChange = (e) => {
const {name, value} = e.target;
setInputs({
...inputs,
[name]: value
})
}
const [users, setUsers] = useState([
{
id: '1',
username: 'sjho0428',
email: 'sjho0428@gmail.com',
active: true
},
{
id: '2',
username: 'tester',
email: 'tester@gmail.com',
active: false
},
{
id: '3',
username: 'everton',
email: 'everton@gmail.com',
active: false
}
]);
const nextId = useRef(4);
const onCreate = () => {
const user = {
id: nextId.current,
username,
email
}
setUsers([...users, user]);
setInputs({
username: '',
email: ''
})
console.log(nextId.current);
nextId.current += 1;
};
const onRemove = id => {
setUsers(
users.filter(user => user.id !== id)
)
};
const onToggle = (id) => {
setUsers(
users.map(user => user.id === id
? {...user, active: !user.active}
:user
)
)
}
const count = useMemo(()=>CountAtivedUsers(users),[users]);
return (
<>
<CreateUser
username={username}
email={email}
onCreate={onCreate}
onChange={onChange}
/>
<UserList users={users} onRemove={onRemove} onToggle={onToggle} />
<div>활성 사용자 수: {count}</div>
</>
)
}
export default App;