Updated:

useState Hook

import { useState } from 'react';

function Counter() {
  // [현재 상태, 상태를 업데이트하는 함수] = useState(초기값)
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

코멘트: useState는 가장 기본적인 Hook으로, 함수형 컴포넌트에서 상태를 관리할 수 있게 해줍니다. 첫 번째 요소는 현재 상태값, 두 번째 요소는 상태를 업데이트하는 함수입니다.

객체 상태 관리

function UserForm() {
  const [user, setUser] = useState({
    name: '',
    email: '',
    age: 0
  });
  
  const handleNameChange = (e) => {
    // 불변성을 유지하며 상태 업데이트
    setUser({
      ...user,
      name: e.target.value
    });
  };
  
  return (
    <form>
      <input
        value={user.name}
        onChange={handleNameChange}
        placeholder="Name"
      />
      {/* 다른 입력 필드들... */}
    </form>
  );
}

코멘트: 객체 상태를 업데이트할 때는 항상 새로운 객체를 생성하여 불변성(immutability)을 유지해야 합니다. 스프레드 연산자(…)를 사용하면 기존 객체의 속성을 복사하고 필요한 부분만 변경할 수 있습니다.

함수형 업데이트

function Counter() {
  const [count, setCount] = useState(0);
  
  const increment = () => {
    // 이전 상태를 기반으로 업데이트 (안전한 방법)
    setCount(prevCount => prevCount + 1);
  };
  
  // 여러 번 호출해도 안전하게 작동
  const incrementThree = () => {
    increment();
    increment();
    increment();
  };
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={incrementThree}>Increment by 3</button>
    </div>
  );
}

코멘트: 이전 상태에 의존하여 상태를 업데이트할 때는 함수형 업데이트를 사용해야 합니다. 이렇게 하면 React의 배치 업데이트 과정에서 발생할 수 있는 문제를 방지할 수 있습니다.

배열 상태 관리

function TodoList() {
  const [todos, setTodos] = useState([
    { id: 1, text: 'Learn React', completed: false },
    { id: 2, text: 'Build a project', completed: false }
  ]);
  
  // 새 할일 추가
  const addTodo = (text) => {
    const newTodo = {
      id: Date.now(),
      text,
      completed: false
    };
    setTodos([...todos, newTodo]);
  };
  
  // 할일 삭제
  const removeTodo = (id) => {
    setTodos(todos.filter(todo => todo.id !== id));
  };
  
  // 할일 완료 상태 토글
  const toggleTodo = (id) => {
    setTodos(todos.map(todo => 
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    ));
  };
  
  return (
    <div>
      <button onClick={() => addTodo('New Task')}>Add Task</button>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>
            <span 
              style=
              onClick={() => toggleTodo(todo.id)}
            >
              {todo.text}
            </span>
            <button onClick={() => removeTodo(todo.id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

코멘트: 배열 상태를 다룰 때도 불변성을 유지해야 합니다. 배열에 항목을 추가할 때는 스프레드 연산자, 삭제할 때는 filter, 업데이트할 때는 map을 사용하는 패턴이 일반적입니다. 직접 배열을 수정하는 push, splice 등의 메서드는 사용하지 않습니다.

Categories:

Updated:

Leave a comment