React useState Hook을 사용하는 방법

8675 단어 reacthooksjavascript
Hook은 v16.8(2018)부터 React에서 사용할 수 있으며 함수 구성 요소가 상태 및 부작용을 관리할 수 있도록 합니다.

기존 코드와 나란히 작동합니다. 다른 많은 훌륭한 기능이 있습니다. Intro to React Hooks 블로그 게시물을 확인하세요.

React는 useState와 같은 몇 가지 내장 Hook을 제공합니다. 이 블로그 게시물은 useState 후크에 관한 것입니다.

💰: Start your cloud journey with $100 in free credits with DigitalOcean!

사용 상태

Let's start with a basic counter as an example. We start from a class component and refactor it to a function component.

Class

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button
          onClick={() =>
            this.setState({ count: this.state.count + 1 })
          }
        >
          Click me
        </button>
      </div>
    );
  }
}

The state starts as { count: 0 } , and we increment state.count when the user clicks a button by calling this.setState() .

기능 구성 요소

A friendly reminder, function components look like this:

const Example = props => {
  // You can use Hooks here!
  return <div />;
};

or like this:

function Example(props) {
  // You can use Hooks here!
  return <div />;
}

Before Hooks these components were often referred to as stateless components , with the introduction of Hooks this has changed.

Hook이란 무엇이며 언제 사용합니까?

A Hook is a function that lets you “hook into” React features. The useState hook lets you add React state to function components.

import React, { useState } from 'react';

function Example() {
  // ...
}

If a function component needs some state, previously (before 2018) you had to convert it to a class component, now you can use a Hook inside the existing function component.

상태 선언

In the class component we initialized state in the constructor by setting this.state to { count: 0 } .

this.state = {
  count: 0,
};

In a function component, we have no this , it's just a function not a class, so we can't use this.setState() . We call the useState Hook directly inside our component:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
  // ...

When you call useState you declare a state variable. In the example above the variable is called count, but it can be anything. Normally, variables “disappear” when the function exits, but state variables are preserved by React.

The argument passed to useState is the initial state. The state doesn't have to be an object.

useState returns a pair of values - the current state and, a function that updates it.

In the example above:

  • We declare a state variable called count
  • Set the initial value of count to 0. React will remember its current value between re-renders, and provide the most recent one.
  • If we want to update the current count, we can call setCount.

읽기 상태

To display the current count in a class, we read this.state.count :

<p>You clicked {this.state.count} times</p>

In a function, we can use count directly:

<p>You clicked {count} times</p>

상태 업데이트 중

In a class, we have to call this.setState() to update the count state:

<button
  onClick={() => this.setState({ count: this.state.count + 1 })}
>
  Click me
</button>

In a function, we already have setCount and count as variables so we don’t need this:

<button onClick={() => setCount(count + 1)}>Click me</button>

함수 구성 요소에 대한 클래스 - 카운터

The entire function component looks like this:

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

대괄호는 무엇을 의미합니까?

The square brackets when we declare a state variable with useState are JavaScript array destructuring.

So this syntax:

const [fruit, setFruit] = useState('banana');

Is destructured to this:

let fruitStateVariable = useState('banana'); // Returns a pair
let fruit = fruitStateVariable[0]; // First item in a pair
let setFruit = fruitStateVariable[1]; // Second item in a pair

When we declare a state variable with useState , it returns a pair — an array with two items. The first item is the current value , and the second is a function that lets us update it.

TL;DR

  • The useState Hook enables function components to be stateful.
  • useState removes complexity and can be used side-by-side with existing code. No need for a big refactor.

Thanks for reading and if you have any questions , use the comment function or send me a message .

If you want to know more about React , have a look at these React Tutorials .

참조(그리고 큰 감사):

React Hooks Intro , ReactJS

좋은 웹페이지 즐겨찾기