React 에서 useState 이란?
React 에서 useState 은 훅(Hook) 에 하나다. 함수 컴포넌트에 상태를 추가하기 위한 훅이다.
useState
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import React, { useState } from 'react'; function ExampleComponent() { // Declare a state variable and a function to update it const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } export default ExampleComponent; |
키 포인트
- 초기값(Initialization): useState(initialValue) 은 상태의 초기값을 가진다.
- 상태 변수(State Variable): 배열의 첫번째 요소는 현재 상태 값이다.
- 업데이터 함수(Updater Function): 배열의 두번째 요소는 상태를 업데이트 하기 위한 함수다.
또 다른 키 포인트는 useState 가 배열로 값을 리턴한다.
여러 예제
여러 상태 값
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function UserProfile() { const [name, setName] = useState(''); const [age, setAge] = useState(0); return ( <div> <input type="text" placeholder="Enter name" value={name} onChange={(e) => setName(e.target.value)} /> <input type="number" placeholder="Enter age" value={age} onChange={(e) => setAge(Number(e.target.value))} /> <p>Name: {name}, Age: {age}</p> </div> ); } |
복잡한 상태 업데이트
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function UserSettings() { const [settings, setSettings] = useState({ theme: 'light', notifications: true }); const toggleTheme = () => { setSettings((prevSettings) => ({ ...prevSettings, theme: prevSettings.theme === 'light' ? 'dark' : 'light', })); }; return ( <div> <p>Current Theme: {settings.theme}</p> <button onClick={toggleTheme}>Toggle Theme</button> </div> ); } |
배열을 상태로 가지는 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function TodoList() { const [todos, setTodos] = useState([]); const addTodo = () => { setTodos([...todos, `Task ${todos.length + 1}`]); }; return ( <div> <button onClick={addTodo}>Add Todo</button> <ul> {todos.map((todo, index) => ( <li key={index}>{todo}</li> ))} </ul> </div> ); } |
팁(Tip)
- 상태를 변경하기 위해서 업데이트 함수(setState) 를 사용해라.
- 복잡한 업데이트의 경우, 상태의 오래된 값을 방지하기 위해 setState의 함수형 형태를 사용해라.
- 상태 객체나 배열을 직접 변경하지 말고 항상 새로운 복사본을 생성하라.