[리액트 공식문서 읽기] ADDING INTERACTIVITY - State: A Component's Memory

JaeHong Jeong·2023년 9월 1일
post-thumbnail

Overview

컴포넌트는 상호 작용의 결과로 화면의 내용을 변경해야 하는 경우가 많다. 양식에 입력하면 입력 필드가 업데이트되고, 이미지 캐러셀에서 ‘다음’을 클릭하면 표시되는 이미지가 변경되고, ‘구매’를 클릭하면 제품이 장바구니에 담기게 된다. 컴포넌트는 현재 입력 값, 현재 이미지, 장바구니 등을 ‘기억’해야 한다. 리액트에서는 이러한 종류의 컴포넌트별 메모리를 상태라고 한다.

When a regular variable isn’t enough

다음은 조각 이미지를 렌더링하는 컴포넌트이다. ‘다음’ 버튼을 클릭하면 index1, 2 등으로 변경되어 다음 조각품이 표시된다. 그러나 이 방법은 작동하지 않는다.

// App.js

import { sculptureList } from './data.js';

export default function Gallery() {
  let index = 0;

  function handleClick() {
    index = index + 1;
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
      <p>
        {sculpture.description}
      </p>
    </>
  );
}
// data.js

export const sculptureList = [{
  name: 'Homenaje a la Neurocirugía',
  artist: 'Marta Colvin Andrade',
  description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
  url: 'https://i.imgur.com/Mx7dA2Y.jpg',
  alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'  
}, {
  name: 'Floralis Genérica',
  artist: 'Eduardo Catalano',
  description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
  url: 'https://i.imgur.com/ZF6s192m.jpg',
  alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
}, {
  name: 'Eternal Presence',
  artist: 'John Woodrow Wilson',
  description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
  url: 'https://i.imgur.com/aTtVpES.jpg',
  alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
}, {
  name: 'Moai',
  artist: 'Unknown Artist',
  description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
  url: 'https://i.imgur.com/RCwLEoQm.jpg',
  alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
}, {
  name: 'Blue Nana',
  artist: 'Niki de Saint Phalle',
  description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
  url: 'https://i.imgur.com/Sd1AgUOm.jpg',
  alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
}, {
  name: 'Ultimate Form',
  artist: 'Barbara Hepworth',
  description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
  url: 'https://i.imgur.com/2heNQDcm.jpg',
  alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
}, {
  name: 'Cavaliere',
  artist: 'Lamidi Olonade Fakeye',
  description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
  url: 'https://i.imgur.com/wIdGuZwm.png',
  alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
}, {
  name: 'Big Bellies',
  artist: 'Alina Szapocznikow',
  description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
  url: 'https://i.imgur.com/AlHTAdDm.jpg',
  alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
}, {
  name: 'Terracotta Army',
  artist: 'Unknown Artist',
  description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
  url: 'https://i.imgur.com/HMFmH6m.jpg',
  alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
}, {
  name: 'Lunar Landscape',
  artist: 'Louise Nevelson',
  description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
  url: 'https://i.imgur.com/rN7hY6om.jpg',
  alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
}, {
  name: 'Aureole',
  artist: 'Ranjani Shettar',
  description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
  url: 'https://i.imgur.com/okTpbHhm.jpg',
  alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
}, {
  name: 'Hippos',
  artist: 'Taipei Zoo',
  description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
  url: 'https://i.imgur.com/6o5Vuyu.jpg',
  alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
}];

handleClick 이벤트 핸들러가 지역 변수 index 를 업데이트하고 있다. 그러나 두 가지 요인으로 해당 변경 사항이 눈에 보이지 않게 된다.

  1. 지역 변수는 렌더링 간에 유지되지 않는다. 리액트가 컴포넌트를 두 번째로 렌더링할 때 처음부터 렌더링한다. 즉, 지역 변수에 대한 변경 사항을 고려하지 않는다.
  2. 지역 변수를 변경해도 렌더링이 트리거되지 않는다. 리액트는 새 데이터로 컴포넌트를 다시 렌더링해야 한다는 것을 인식하지 못한다.

새 데이터로 컴포넌트를 업데이트하려면 다음 두 가지 작업이 수행되어야 한다.

  1. 렌더링 간에 데이터를 유지한다.
  2. 리액트를 트리거하여 새 데이터로 컴포넌트 렌더링한다.

useState 훅은 다음 두 가지를 제공한다.

  1. 렌더링 간 데이터를 유지하기 위한 상태 변수이다.
  2. 변수를 업데이트하고 리액트를 트리거하여 컴포넌트를 다시 렌더링하는 상태 설정기 함수이다.

Adding a state variable

상태 변수를 추가하려면 파일 상단에 React에서 useState 를 가져온다.

import { useState } from 'react';

그런 다음 다음 줄을 바꾼다.

let index = 0;

=>>

const [index, setIndex] = useState(0);

index 는 상태 변수이고 setIndex 는 setter 함수이다.

여기서 [, ] 구문을 배열 구조 분해라고 하며 이를 사용하면 배열에서 값을 읽을 수 있다. useState 에서 반환된 배열에는 항상 정확히 두개의 항목이 있다.

다음은 handleClick 에서 함께 작동하는 방식이다.


function handleClick() {
  setIndex(index + 1);
}

이제 ‘다음’ 버튼을 클릭하면 현재 조각품이 전환된다.

// App.js

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);

  function handleClick() {
    setIndex(index + 1);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
      <p>
        {sculpture.description}
      </p>
    </>
  );
}
// data.js

export const sculptureList = [{
  name: 'Homenaje a la Neurocirugía',
  artist: 'Marta Colvin Andrade',
  description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
  url: 'https://i.imgur.com/Mx7dA2Y.jpg',
  alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'  
}, {
  name: 'Floralis Genérica',
  artist: 'Eduardo Catalano',
  description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
  url: 'https://i.imgur.com/ZF6s192m.jpg',
  alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
}, {
  name: 'Eternal Presence',
  artist: 'John Woodrow Wilson',
  description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
  url: 'https://i.imgur.com/aTtVpES.jpg',
  alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
}, {
  name: 'Moai',
  artist: 'Unknown Artist',
  description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
  url: 'https://i.imgur.com/RCwLEoQm.jpg',
  alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
}, {
  name: 'Blue Nana',
  artist: 'Niki de Saint Phalle',
  description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
  url: 'https://i.imgur.com/Sd1AgUOm.jpg',
  alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
}, {
  name: 'Ultimate Form',
  artist: 'Barbara Hepworth',
  description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
  url: 'https://i.imgur.com/2heNQDcm.jpg',
  alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
}, {
  name: 'Cavaliere',
  artist: 'Lamidi Olonade Fakeye',
  description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
  url: 'https://i.imgur.com/wIdGuZwm.png',
  alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
}, {
  name: 'Big Bellies',
  artist: 'Alina Szapocznikow',
  description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
  url: 'https://i.imgur.com/AlHTAdDm.jpg',
  alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
}, {
  name: 'Terracotta Army',
  artist: 'Unknown Artist',
  description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
  url: 'https://i.imgur.com/HMFmH6m.jpg',
  alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
}, {
  name: 'Lunar Landscape',
  artist: 'Louise Nevelson',
  description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
  url: 'https://i.imgur.com/rN7hY6om.jpg',
  alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
}, {
  name: 'Aureole',
  artist: 'Ranjani Shettar',
  description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
  url: 'https://i.imgur.com/okTpbHhm.jpg',
  alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
}, {
  name: 'Hippos',
  artist: 'Taipei Zoo',
  description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
  url: 'https://i.imgur.com/6o5Vuyu.jpg',
  alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
}];

Meet your first Hook

리액트에서 useState 와 “use"로 시작하는 다른 모든 함수를 Hook이라고 한다.

Hooks는 리액트가 렌더링되는 동안에만 사용할 수 있는 특수 기능이다. 이를 통해 다양한 리액트 기능에 ‘연결’할 수 있다.

상태는 이러한 기능 중 하나일 뿐이지만 나중에 다른 hooks를 만나게 된다.

💡 Pitfall

Hook(use 로 시작하는 함수)는 컴포넌트의 최상위 수중이나 자체 Hook에서만 호출할 수 있다. 조건, 루프 또는 기타 중첩 함수 내에서는 Hooks를 호출할 수 없다. Hook는 함수이지만 컴포넌트의 요구 사항에 대한 무조건적인 선언으로 생각하는 것이 도움된다. 파일 상단에서 모듈을 “가져오는”방법과 유사하게 컴포넌트 상단에서 리액트 기능을 “사용”한다.

Anatomy of useState

useState 를 호출하면 리액트에 이 컴포넌트가 무엇인가를 기억하길 원한다고 말하는 것이다.

const [index, setIndex] = useState(0);

이 경우 리액트가 index 를 기억하기를 원한다.

💡 Note

규칙은 이 쌍의 이름을 const [something, setSomething] 과 같이 지정하는 것이다. 원하는 대로 이름을 지정할 수 있지만 규칙을 사용하면 프로젝트 전체에서 작업을 더 쉽게 이해할 수 있다.

useState 의 유일한 인수는 상태 변수 초기 값이다. 이 예에서는 useState(0) 를 사용하여 index 의 초기값 을 0 으로 설정한다.

컴포넌트가 렌더링될 때 마다 useState 는 두 가지 값을 포함하는 배열을 제공한다.

  1. 저장한 값이 포함된 상태 변수(index)이다.
  2. 상태 변수를 업데이트하고 리액트를 트리거하여 컴포넌트를 다시 렌더링할 수 있는 상태 설정기 함수(setIndex)

실제 상황은 다음과 같다.

const [index, setIndex] = useState(0);
  1. 컴포넌트가 처음 렌더링된다. index 의 초기 값으로 useState0 을 전달 했으므로 [0, setIndex] 가 반환된다. 리액트는 0 이 최신 상태값임을 기억한다.
  2. 상태를 업데이트한다. 사용자가 버튼을 클릭하면 setIndex(index + 1) 가 호출된다. index0 이므로 setIndex(1) 이다. 이는 리액트가 이제 index1 임을 기억하고 또 다른 렌더링을 트리거 하도록 지시한다.
  3. 컴포넌트의 두 번째 렌더링. 리액트는 여전히 useState(0) 를 볼 수 있지만, 리액트는 사용자가 index1 로 설정했다는 것을 기억하기 때문에 대신 [1, setIndex] 를 반환한다.
  4. And so on!

Giving a component multiple state variables

하나의 컴포넌트에 원하는 만큼 유형의 상태 변수를 가질 수 있다. 이 컴포넌트에는 ‘Show details’를 클릭하면 전환되는 숫자 index 와 불리언 showMore 라는 두 가지 상태 변수가 있다.

// App.js

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);
  const [showMore, setShowMore] = useState(false);

  function handleNextClick() {
    setIndex(index + 1);
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleNextClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <button onClick={handleMoreClick}>
        {showMore ? 'Hide' : 'Show'} details
      </button>
      {showMore && <p>{sculpture.description}</p>}
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
    </>
  );
}
// data.js

export const sculptureList = [{
  name: 'Homenaje a la Neurocirugía',
  artist: 'Marta Colvin Andrade',
  description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
  url: 'https://i.imgur.com/Mx7dA2Y.jpg',
  alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'  
}, {
  name: 'Floralis Genérica',
  artist: 'Eduardo Catalano',
  description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
  url: 'https://i.imgur.com/ZF6s192m.jpg',
  alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
}, {
  name: 'Eternal Presence',
  artist: 'John Woodrow Wilson',
  description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
  url: 'https://i.imgur.com/aTtVpES.jpg',
  alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
}, {
  name: 'Moai',
  artist: 'Unknown Artist',
  description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
  url: 'https://i.imgur.com/RCwLEoQm.jpg',
  alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
}, {
  name: 'Blue Nana',
  artist: 'Niki de Saint Phalle',
  description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
  url: 'https://i.imgur.com/Sd1AgUOm.jpg',
  alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
}, {
  name: 'Ultimate Form',
  artist: 'Barbara Hepworth',
  description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
  url: 'https://i.imgur.com/2heNQDcm.jpg',
  alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
}, {
  name: 'Cavaliere',
  artist: 'Lamidi Olonade Fakeye',
  description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
  url: 'https://i.imgur.com/wIdGuZwm.png',
  alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
}, {
  name: 'Big Bellies',
  artist: 'Alina Szapocznikow',
  description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
  url: 'https://i.imgur.com/AlHTAdDm.jpg',
  alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
}, {
  name: 'Terracotta Army',
  artist: 'Unknown Artist',
  description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
  url: 'https://i.imgur.com/HMFmH6m.jpg',
  alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
}, {
  name: 'Lunar Landscape',
  artist: 'Louise Nevelson',
  description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
  url: 'https://i.imgur.com/rN7hY6om.jpg',
  alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
}, {
  name: 'Aureole',
  artist: 'Ranjani Shettar',
  description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
  url: 'https://i.imgur.com/okTpbHhm.jpg',
  alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
}, {
  name: 'Hippos',
  artist: 'Taipei Zoo',
  description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
  url: 'https://i.imgur.com/6o5Vuyu.jpg',
  alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
}];

이 예제의 indexshowMore 와 같이 상태가 관련이 없는 경우 여러 상태 변수를 갖는 것이 좋다. 그러나 두 개의 상태 변수를 함께 변경하는 경우가 많다면 하나로 결합하는 것이 더 쉬울 수 있다. 예를 들어, 필드가 많은 양식 있는 경우 필드당 상태 변수를 보유하는 것보다 객체를 보유하는 단일 상태 변수를 갖는 것이 더 편리하다. Choosing the State Structure.

💡 DEEP DIVE

리액트는 어떤 상태를 반환할지 어떻게 알 수 있나요?

useState 호출이 자신이 참조하는 상태 변수에 대한 정보를 받지 못한다는 사실을 눈치챘을 것이다. useState 에 전달되는 ‘식별자’가 없는데 어떤 상태 변수를 반환할지 어떻게 알 수 있나? 함수를 구문 분석하는 것과 같은 마법에 의존하나? 아니다.

대신, 간결한 구문을 활성하기 위해 Hooks는 동일한 컴포넌트를 렌더링할 때마다 안정적인 호출 순서를 사용하한다. 위의 규칙(”최상위 수준에서만 Hooks를 호출”)을 따르면 Hooks는 항상 같은 순서로 호출되기 때문에 실제로는 잘 작동한다. 또한 linter plugin은 대부분의 실수를 잡아낸다.

내부적으로 리액트는 모든 컴포넌트에 대한 상태 쌍 배열을 보유한다. 또한 렌더링 전에 0 으로 설정된 현재 쌍 인덱스를 유지한다. useState 를 호출할 때마다 리액트는 다음 상태 쌍을 제공하고 인덱스를 증가시킨다. React Hooks: Not Magic, Just Arrays. 에서 자세히 알아 볼 수 있다.

이 예에서는 리액트를 사용하지 않지만 useState 가 내부적으로 어떻게 작동하는지에 대한 아이디어를 제공한다.

https://codesandbox.io/s/t628gw?file=/index.js&utm_medium=sandpack

리액트를 사용하기 위해 이해할 필요는 없지만 이것이 유용한 정신 모델이란느 것을 알게 될 것이다.

State is isolated and private

상태는 화면의 컴포넌트 인스턴스에 대해 지역적이다. 즉, 동일한 컴포넌트를 두 번 렌더링하면 각 복사본은 완전히 격리된 상태가 된다. 둘 중 하나를 변경해도 다른 하나에는 영향을 미치지 않는다.

이 예에서는 이전의 Gallery 컴포넌트가 논리 변경 없이 두 번 렌더링된다.

이것 이 상태가 모듈 상단에서 선언할 수 있는 일반 변수와 다른 점이다. 상태는 특정 함수 호출이나 코드의 위치에 묶여 있지 않지만 화면의 특정 위치에 ‘local’이다. 두 개의 <Gallery /> 컴포넌트를 렌더링 했으므로 해당 상태가 별도로 저장된다.

또한 Page 컴포넌트가 Gallery 컴포넌트 상태나 상태 여부에 대해 아무것도 ‘알지’ 못하는 방법도 확인해라. props와 달리 state는 이를 선언하는 컴포넌트에 완전히 비공개이다. 상위 컴포넌트는 이를 변경할 수 없다. 이를 통해 나머지 컴포넌트에 영향을 주지 않고 컴포넌트에 상태를 추가하거나 제거할 수 있다.

두 갤러리의 상태를 동기화 상태로 유지하려면 어떻게 해야할까? 리액트에서 이를 수행하는 올바른 방법은 하위 컴포넌트에서 상태를 제거하고 이를 가장 가까운 공유 상위 컴포넌트에 추가하는 것이다. 다음 몇 페이지에서는 단일 컴포넌트의 상태를 구성하는 데 중점을 두지만 컴포넌트 간 사앹 공유에서 이 주제로 다시 돌아간다.

Recap

  • 컴포넌트가 렌더링 간의 일부 정보를 ‘기억’해야할 때 상태 변수를 사용한다.
  • 상태 변수는 useState Hook을 호출하여 선언된다.
  • Hooks는 use 로 시작하는 특수 함수이다. 이를 통해 상태와 같은 리액트 기능에 ‘연결’할 수 있다.
  • Hooks는 import를 상기시켜 줄 수 있다. 무조건 호출해야한다. useState 를 포함한 Hooks호출은 컴포넌트 최상위 수준이나 다른 Hooks에서만 유효하다.
  • useState Hooks는 현재 상태와 이를 업데이트하는 함수 한쌍의 값을 반환한다.
  • 상태 변수는 두 개 이상 있을 수 있다. 내부적으로 리액트는 순서대로 일치시킨다.
  • 상태는 컴포넌트에만 적용된다. 두 위치에서 렌더링하는 경우 각 복사본은 고유한 상태를 갖는다.
profile
반갑습니다.

0개의 댓글