React useState

React/React 2022. 6. 4. 00:05
728x90

Hook은 React 버전 16.8(2019년)부터 React 요소로 새로 추가되었다.

https://ko.reactjs.org/docs/hooks-effect.html 가 React 에서 기본 제공하는 내용 설명이다.

함수형 컴포넌트의 주요 단점은 state 와 라이프사이클 API 의 사용이 불가능하다는 점이었는데, 리액트 16.8 업데이트 이후 Hooks 기능이 도입되면서 해결되었다.

현재 리액트 공식 매뉴얼에서는, Class형 컴포넌트보다는 Function형 컴포넌트와 Hooks로 React 프로젝트를 만들기를 권장하고 있다.

 

App.js

import logo from './logo.svg';
import './App.css';
import Example1 from "./components/Example1";
import Example2 from "./components/Example2";
import Example3 from "./components/Example3";
 
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Example1 />
        <Example2 />
        <Example3 />
      </header>
    </div>
  );
}
 
export default App;

 

Example1.jsx

파일명을 생성하고 파일 안에서 rcc 를 입력하고 TAB 키를 누르면 자동완성된 기본 컴포넌트가 만들어진다.

클래스형 컴포넌트에서는 render함수가 꼭 있어야 한다.

import React, {Component} from 'react';
 
class Example1 extends Component {
    state = {count: 0};
 
    render() {
        const { count } = this.state;
        return (
            <div>
                <p>You clicked {count} times.</p>
                <button onClick={this.click}>Click me</button>
            </div>
        );
    }
 
    click = () => {
        this.setState({
            count: this.state.count + 1
        });
    };
}
 
export default Example1;

 

Example2.jsx

- useState 함수의 인자에는 상태의 초기값을 넣어 준다. 초기값은 숫자, 문자열, 객체, 배열 등

- 배열 비구조화 할당 const [count, setCount] 에서 첫번째 원소는 현재 상태이고, 두번째 원소는 상태를 바꾸어주는 함수이다. 이 함수를 Setter 함수라고 부른다.

- 하나의 useState 함수는 하나의 상태 값만 관리할 수 있다.

  컴포넌트에서 관리해야 할 상태가 여러 개라면 useState를 여러 번 사용하면 된다.

- state 는 컴포넌트 자체적으로 지닌 값으로 컴포넌트 내부에서 값을 업데이트할 수 있다.

import React from 'react';
 
const Example2 = () => {
    const [count, setCount] = React.useState(0);
 
    function click() {
        setCount(count + 1);
    }
 
    return (
        <div>
            <p>You clicked {count} times.</p>
            <button onClick={click}>Click me</button>
        </div>
    );
};
 
export default Example2;

 

Exampe3.jsx

// rsc 입력하고 Tab 키를 누른다.
import React from 'react';
 
const Example3 = () => {
    // useState : state를 대체할 수 있다.
    const [state, setState] = React.useState({count: 0});
 
    function click() {
        setState((state) => ({
            count: state.count + 1,
        }));
    }
 
    return (
        <div>
            <p>You clicked {state.count} times.</p>
            <button onClick={click}>Click me</button>
        </div>
    );
};
 
export default Example3;

 

 

이제 bootstrap4 를 적용해보자.

# Step1 – Install Bootstrap 4
npm install bootstrap --save

 

App.js

import logo from './logo.svg';
import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import Example1 from "./components/Example1";
import Example2 from "./components/Example2";
import Example3 from "./components/Example3";
 
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Example1 />
        <Example2 />
        <Example3 />
      </header>
    </div>
  );
}
 
export default App;

 

 

Exampl1.jsx

import React, {Component} from 'react';
 
class Example1 extends Component {
    state = {count: 0};
 
    render() {
        const { count } = this.state;
        return (
            <div className="col-md-12 text-center">
                <p>You clicked {count} times.</p>
                <button className="btn btn-primary" onClick={this.click}>Click me</button>
            </div>
        );
    }
 
    click = () => {
        this.setState({
            count: this.state.count + 1
        });
    };
}
 
export default Example1;

 

 

 

'React > React' 카테고리의 다른 글

React Query String  (0) 2022.06.08
React Router v6  (0) 2022.06.07
React 값 전달(부모 → 자식, 자식 → 부모)  (0) 2022.06.03
React Event 처리하기  (0) 2022.05.29
React Component 만들기  (0) 2022.05.28
블로그 이미지

Link2Me

,