본문 바로가기
프로그래밍/React

[React] useState

by YuminK 2023. 11. 27.

useState

useState is a React Hook that lets you add a state variable to your component.

 

Returns 

useState returns an array with exactly two values:

 

The current state. During the first render, it will match the initialState you have passed.

The set function that lets you update the state to a different value and trigger a re-render.

 

useState는 초기값과 re-render를 트리거하는 set함수를 넘겨준다. 

초기값으로 object를 넘길 수도 있고 스프레드 형태로 이전 값을 넣고 특정 값만 변경할 수 있다. 

 

함수나 값을 넘길 수 있다. 

 

Caveats 

The set function only updates the state variable for the next render. If you read the state variable after calling the set function, you will still get the old value that was on the screen before your call.

 

React batches state updates. It updates the screen after all the event handlers have run and have called their set functions. This prevents multiple re-renders during a single event. 

 

이 부분은 flutter의 provider에서 notifiyListeners와 비슷하네. 모았다가 한번에 처리.

 

Calling the set function does not change the current state in the already executing code:

 

function handleClick() {

  setName('Robin');

  console.log(name); // Still "Taylor"!

}

 

다음 프레임에 바뀐다는 게 엄청 신기하다.

 

function handleClick() {

  setAge(a => a + 1); // setAge(42 => 43)

  setAge(a => a + 1); // setAge(43 => 44)

  setAge(a => a + 1); // setAge(44 => 45)

}

업데이터 함수는 큐에 담아서 처리한다고 한다. 

 

 In React, state is considered read-only, so you should replace it rather than mutate your existing objects. For example, if you have a form object in state, don’t mutate it:

 

// 🚩 Don't mutate an object in state like this:

form.firstName = 'Taylor';

Instead, replace the whole object by creating a new one:

 

// ✅ Replace state with a new object

setForm({

  ...form,

  firstName: 'Taylor'

});

 

상태를 수정해서 다시 그려라 (X)

상태를 수정한 객체를 다시 만들어라 그리고 읽어라. (O)

 

리액트는 마치 provider를 사용하지 않는 날것 그대로의 flutter 방식과 유사하게 상태관리를 하는 느낌이다.

근데 flutter에서는 클래스가 상태에 처리하는 변수를 저장하는 반면, React에서는 상태의 저장이 아니라 상태를 바꾸고 다시 시작하는 느낌이랄까(왜냐면 함수잖아 근본적으로)

 

함수가 클래스처럼 상태를 저장하겠다는 것 자체에 패러다임 차이가 있는 듯 싶다.

 

const [todos, setTodos] = useState(createInitialTodos());

이런 행위는 리소스를 많이 먹을 가능성이 있다.

createInitialTodos()에 반환값은 초기에 1번 사용되지만, 함수는 매 렌더마다 처리되기 때문이다. 

 

const [todos, setTodos] = useState(createInitialTodos);

함수를 넘기는 방식은 괜찮다.

 

현재 프롭스 혹은 다른 상태에서 완전히 다시 계산될 수 있는 경우 useMemo 훅을 사용해라. (캐싱이 필요한 경우)

전체 컨포넌트 트리의 상태를 재설정하고 싶다면, 다른 키를 컴포넌트에 넘겨라.

 

Calling the set function of another component during rendering is an error.

다른 컴포넌트의 set을 호출하는 것은 에러

 

When you call the set function during render, React will re-render that component immediately after your component exits with a return statement

렌더링 중에 set이 호출될 경우 컴포넌트가 끝난 후(렌더링이 끝난 후) 다시 렌더링된다.

 

// 🚩 Wrong: calls the handler during render

return <button onClick={handleClick()}>Click me</button>

 

// ✅ Correct: passes down the event handler

return <button onClick={handleClick}>Click me</button>

 

// ✅ Correct: passes down an inline function

return <button onClick={(e) => handleClick(e)}>Click me</button>

 

setTodos(prevTodos => {

  // 🚩 Mistake: mutating state

  prevTodos.push(createTodo());

});

 

setTodos(prevTodos => {

  // ✅ Correct: replacing with new state

  return [...prevTodos, createTodo()];

});

 

Only component, initializer, and updater functions need to be pure. Event handlers don’t need to be pure, so React will never call your event handlers twice.

 

상태를 바꾸지 말고 새로 생성해서 넣으라고 계속 이야기하고 있음. 리액트에서는 Strict 모드에서 함수를 2번씩 호출하는데, pure 하지 않은 함수에서 잘못된 동작(실수)을 보고 고치도록 유도하기 위함이라고 한다. 

 

https://react.dev/reference/react/useState

'프로그래밍 > React' 카테고리의 다른 글

[React] useRef  (0) 2023.11.28
[React] useEffect  (0) 2023.11.28
[React] 리액트 개요  (0) 2023.11.27
[React] 이미지 업로드 및 미리보기  (0) 2023.09.09
[React] 페이지 이동하기  (0) 2023.09.06

댓글