끄적끄적 코딩
Published 2020. 11. 5. 06:50
[React] Hooks, 코드 비교 React

Hooks란?
=> 함수컴포넌트에서 ref와 state를 사용 가능하게 하는 기능

const [x, y] = React.useState(z); 
=> hoos에서 state 선언
     x - state
     y - x state의 setState역할
     z - 초기값

setState(a)
=> state값을 a로 변경 (setState는 위 state선언에서 y부분)

const inputRef = React.useRef(null)
inputReft.current.focus();
<input ref={inputRef}/>
=> input태그에 focus 설정


class, hooks 차이점
- state, setState, Ref 사용이 다름
- hooks는 함수컴포넌트 전체가 다시 렌더링되서 조금 더 느릴 수 있음 (렌더링은 state가 변경될 때 발생)

구구단 class code

<html>
  <head>
    <meta charset="UTF-8" />
    <title>구구단</title>
    <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      class GuGuDan extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            first: Math.ceil(Math.random() * 9),
            second: Math.ceil(Math.random() * 9),
            value: "",
            result: "",
          };
        }

        onSubmit = (e) => {
          e.preventDefault();
          if (
            parseInt(this.state.value) ===
            this.state.first * this.state.second
          ) {
            this.setState((prevState) => {
              return {
                result: prevState.value + " 정답!",
                first: Math.ceil(Math.random() * 9),
                second: Math.ceil(Math.random() * 9),
                value: "",
              };
            });
          } else {
            this.setState((prevState) => {
              return {
                result: "땡",
                value: "",
              };
            });
          }
          this.input.focus();
        };

        onChange = (e) => {
          // input 입력
          this.setState({ value: e.target.value });
        };

        onRefInput = (c) => {
          this.input = c;
        };

        input;

        render() {
          return (
            <React.Fragment>
              <div>
                {this.state.first}곱하기{this.state.second}는?
              </div>
              <form onSubmit={this.onSubmit}>
                <input
                  ref={this.onRefInput}
                  type="number"
                  value={this.state.value}
                  onChange={this.onChange}
                />
                <button>입력!</button>
              </form>
              <div>{this.state.result}</div>
            </React.Fragment>
          );
        }
      }
    </script>
    <script type="text/babel">
      ReactDOM.render(<GuGuDan />, document.querySelector("#root"));
    </script>
  </body>
</html>

 

구구단 hooks code

<html>
    <head>
        <meta charset="UTF-8" />
        <title>구구단</title>
        <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>  
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
        <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    </head>
    <body>
        <div id="root"></div>
        <script type="text/babel">
            const GuGuDan = () => {
                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);

                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("");
                    } else {
                        setResult("땡");
                        setValue("");
                    }
                    inputRef.current.focus();
                }

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

                return (
                    <React.Fragment>
                        <div>{first} 곱하기 {second}는?</div>
                        <form onSubmit={onSubmitForm}>
                            <input ref={inputRef} onChange={onChangeInput} value={value}/>
                            <button>입력!</button>
                        </form>
                        <div id="result">{result}</div>
                    </React.Fragment>
                );
            }
        </script>
        <script type="text/babel">
            ReactDOM.render(<GuGuDan />, document.querySelector("#root"));
        </script>
    </body>
</html>

 

 


해당 게시글은 www.youtube.com/watch?v=V3QsSrldHqI&list=PLcqDmjxt30RtqbStQqk-eYMK8N-1SYIFn&index=1&ab_channel=ZeroChoTV 의 강의내용을 기반으로 공부한 내용을 정리한 글입니다.

검색 태그