React

Hooks

youngseokim_kr 2021. 11. 22. 20:47

Basic Hooks - useState, useEffect

기본 class를 사용하는 방법에서

useState를 사용해서

이런식으로 가능하다.

import logo from './logo.svg';
import './App.css';
import Example1 from './components/Example1';
import Example2 from './components/Example2';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Example1 />
        <Example2 />
      </header>
    </div>
  );
}

export default App;

App.js 파일이다.

결과는 똑같이 잘 출력되는걸 확인 가능하다.

import React from 'react';


//useState => count
//useState => {count : 0};
export default function Example3() {

    const [state, setState] = React.useState({count : 0});

  return (
    <div>
      <p>You clicked { state.count } times</p>
      <button onClick={click}>Click me</button>
    </div>
  );

  function click() {
    setState( (state) => {
      return {
        count:state.count+1,
      };
    });
  }
}

3번째 예시.

useEffect

useState - state를 대체할 수 있다.

useEffect - 라이프 사이클 훅을 대체 할 수 있다.

componentDidMount, componentDidUpdate, componentWillUnmount

import React from 'react';

export default function Example5() {

    const [count, setCount] = React.useState(0);

    React.useEffect(() => {
      console.log("componentDidMount ",count);

      return () => {
        //cleanup 
        //componentWillUnmount
      };
    }, []);   //빈 배열은 최초에 한번만 실행

    React.useEffect(() => {
      console.log("componentDidMount & componentDidUpdate by count",count);

      return () => {
        //cleanup
        console.log('cleanup by count', count);
      }
    }, [count]);


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

  function click() {
    setCount(count+1);
  }
}

 

'React' 카테고리의 다른 글

Additional Hooks  (0) 2021.11.23
custom Hooks  (0) 2021.11.23
controlled component , uncontrolled component  (0) 2021.11.22
JS 로 라우팅 이동하기  (0) 2021.11.21
JSX 링크로 라우터 이동  (0) 2021.11.21