React Basic - 7. Hooks 이용하기

Bloooooooooooooog..·2023년 6월 19일

Hooks

최신 트랜드는 클래스를 사용하지 않고 hooks를 이용해서 리액트를 사용한다. hooks는 함수형과 연관되어 있다.

함수형 컴포넌트

ref와 setState를 사용하지 않는 컴포넌트는 함수형 컴포넌트를 이용해서 간단하게 표현할 수 있다.

<body>
    <div id="root"></div>
<script type="text/babel">

    const GuGuDan = ()=>{
        return <div>Hello Hooks</div>
    }
</script>
<script type="text/babel">
    ReactDOM.render(<GuGuDan/>, document.querySelector('#root'));
</script>
</body>

매우 간단하게 화면에 출력할 수 있다.

이렇게 간단한 함수형 컴포넌트에 ref와 setState를 표현할 수 있게 만든 것이 hooks라고 생각하면 된다.

이전에 사용하던 class 사용 방식은 hook로 바꾸면 아래와 같다

<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);
        // 위와 같은 방식으로 초기값을 설정한다. 
        // 반드시 컴포넌트 안에 초기화 선언을 해준다
        // ref는 useRef를 이용해서 DOM에 접근한다.
        const onChangeInput = e => {
            setValue(e.target.value);
        };
        // 함수에서 내부에 set을 이용해서 값을 지정한다. 

        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("오답" + value);
                setValue('');
                inputRef.current.focus();

            }
        };
        
        // 기존에 클래스 방식으로 선언해준 스테이트를 함수형으로 바꾸어준다



        return  (
            <React.Fragment>
                <div>{first} 곱하기 {second}?</div>
                <form onSubmit={onSubmitForm}>
                    <input ref={inputRef} onChange={onChangeInput} value={value}/>
                    <button type="submit">입력</button>
                </form>
                <div id="result">{result}</div>  
            </React.Fragment>
        );
    }

</script>
<script type="text/babel">
    ReactDOM.createRoot(document.querySelector('#root')).render(<GuGuDan/>);
</script>
</body>

훨씬 간결해지고 사용도 편해졌다.

단점

Hooks 사용이 장점만 있는 것은 아니다. Hooks 방식은 state가 바뀌면 함수 자체가 모두 다시 시작되기 때문에 조금 더 느릴 수가 있다.

React에서의 주의사항

react에서 class, for과 html상의 class와 for를 구분하기 위해서 react에선 return하는 코드에서 html 태그의 class는 className으로 for는 htmlFor로 바꾸어 사용한다.

profile
공부와 일상

0개의 댓글