useReducer로 복잡한 상태 처리하기

이동욱

2022/04/16

Categories: 리액트 Tags: 프론트엔드

import {useState} from "react";

const firstUser = {
    id: "0391-3233-3201",
    firstName: "Bill",
    lastName: "Wilson",
    city: "Missoula",
    state: "Montana",
    email: "bwilson@mtnwilsons.com",
    admin: false
}

function User() {
    const [user, setUser] = useState(firstUser);

    return (
        <p>Email: {user.email}</p>
        <p>Location: {user.city}, {user.state}</p>
        <button>make admin</button>
    )
}
<button
    onClick={() => {setUser({ admin: true }); }}
>
    Make Admin
</button>
<button onClick={() => {setUser({ ...user, admin: true); }}>
  Make Admin
</button>
function User() {
    const [user, setUser] = useReducer(
        (user, newDetails) => ({...user, ...newDetails }),
        firstUser
    );
}

참고 문헌


>> Home