Web/React

React : Hooks 사용. (Class와의 차이점) useState, useEffect

Jun_N 2020. 7. 28. 11:26

 

Hook을 쓰는 이유!?

class를 쓰지말고 함수로, 함수 컴포넌트에서도 state랑 ref를 쓰기 위해 만든 것.

 

const GuGuDan = () => {
        //state 선언시 함수 안에다가 써야한다.
        //use로 시작하면 hooks다.
        //비구조화 할당(= 구조 분해 할당 방식)
        const [first, setFirst] = React.useState(Math.ceil(Math.random() * 9));
        const [second, setSecond] = React.useState(
          Math.ceil(Math.random() * 9)
        );
        const [value, setValue] = React.useState("");
        const [result, setResult] = React.useState("");
}
	

class를 쓰지않고 const로 함수를 선언한다.

 

setState를 사용하려는 것은 const로 만들어 준다.

useState의 ()안에는 초기값을 설정해 주면 된다.

first라는 state를 숫자 랜덤값으로 초기 설정해준다는 뜻이며, setFirst를 통해 접근가능하다. (this.state.first 로 안해도 됨)

setResult("정답: " + value);
setFirst(Math.ceil(Math.random() * 9));
setSecond(Math.ceil(Math.random() * 9));
setValue("");

 

 

Ref 사용하는 방법

const inputRef = React.useRef(null); //useRef로 Dom에 접근.

함수 안에다가 선언해주고 사용하려는 곳에 다음과 같이 사용한다.

inputRef.current.focus();

이때 current는 꼭 붙여줘야 한다.

 

 

* state를 바꾸면 함수 전체가 다시 실행되므로 class를 사용할 때보다 느릴 수도 있다.

*id="" 을 쓰는 이유는 react에서는 class -> className를 써야한다.

*같은 이유로 for -> htmlFor

 

<전체 코드>

<!DOCTYPE html>
<html lang="ko">
  <head>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

    <meta charset="UTF-8" />
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      // react는 hooks를 더 많이 씀.
      const GuGuDan = () => {
        //state 선언시 함수 안에다가 써야한다.
        //use로 시작하면 hooks다.
        //비구조화 할당(= 구조 분해 할당 방식)
        const [first, setFirst] = React.useState(Math.ceil(Math.random() * 9));
        const [second, setSecond] = React.useState(
          Math.ceil(Math.random() * 9)
        );
        const [value, setValue] = React.useState("");
        const [result, setResult] = React.useState("");
        const inputRef = React.useRef(null); //useRef로 Dom에 접근.

        const onSubmitForm = (e) => {
          e.preventDefault();
          if (parseInt(value) === first * second) {
            setResult("정답: " + value);
            setFirst(Math.ceil(Math.random() * 9));
            setSecond(Math.ceil(Math.random() * 9));
            setValue("");
            inputRef.current.focus();
          } else {
            setResult("땡! ");
            setValue("");
            inputRef.current.focus();
          }
        };

        const onChangeInput = (e) => {
          setValue(e.target.value);
        };

        //id="" 을 쓰는 이유는 react에서는 class -> className를 써야한다.
        //같은 이유로 for -> htmlFor
        return (
          <>
            <div>
              {first} 곱하기 {second}는?
            </div>
            <form onSubmit={onSubmitForm}>
              <input ref={inputRef} onChange={onChangeInput} value={value} />
              <button>입력! </button>
            </form>
            <div id="result">{result}</div>
          </>
        );
      };
    </script>

    <script type="text/babel">
      ReactDOM.render(<GuGuDan />, document.querySelector("#root")); //LikeButton을 root안에다가 그리겠다.
    </script>
  </body>
</html>

 

useEffect 

useEffect는 life cycle에서 rendering 이후에 처리되는 값들을 처리할 수 있게 해준다.

useEffect(() => {
   console.log("hi");
  });

rendering이 될 때마다 hi가 콘솔창에 출력되는 것을 확인할 수 있다.

[props.source] 부분을 지정하면 저 부분이 rendering 되면 useEffect를 실행해준다는 뜻이다.