react - useRef

yj k·2023년 4월 20일
0

React

목록 보기
14/27

useRef

01_local-var-useref

useRef는 참조할 객체를 만든다.

console.log(useRef(0));를 찍어보면 콘솔에 객체가 찍힌다.
그 안에 current 프로퍼티가 있다.
그 객체가 가진 현재 값을 의미한다.

지역변수 variable은 값을 저장하지 못하기 때문에 랜더링 시
0으로 초기화된다.

이때 useRef의 current프로퍼티를 활용한
랜더링과 무관하게 변경 될 수 있는 값(지역변수 variable) 사용 시 값을 저장할 수 있도록하는 코드


        const { useState, useRef } = React;

        function Counter() {

            const [count, setCount] = useState(0);
            let variable = 0;
            const countRef = useRef(0);

            console.log('Counter 랜더링 됨...');

            const increaseCount = () => {
                setCount(count + 1);
            };

            const increaseVariable = () => {
                variable += 1;
                console.log(`variable : ${variable}`);
            }

            const increaseCountRef = () => {
                countRef.current = countRef.current + 1;
                console.log(`current : ${countRef.current}`);
            }

            return (
                <>
                    <h1> count : { count } </h1>
                    <h1> variable : { variable } </h1>
                    <h1> countRef.current : { countRef.current } </h1>
                    <button onClick={ increaseCount }>count 증가</button>
                    <button onClick={ increaseVariable }>variable 증가</button>
                    <button onClick={ increaseCountRef }>countRef.current 증가</button>
                </>
            );

        }




02_inputref

특정 input에 포커스를 주고싶을 경우 DOM에 접근해야하는데 이를 위해서도 useRef를 사용할 수 있다.

const { useState, useRef, useEffect } = React;

        function LoginComponent() {

            const [form, setForm] = useState({
                username : '',
                password : ''
            });

            const usernameRef = useRef();
            // 랜더링 이전에 동작이기 때문에 최초 출력은 undefined가 나온다. 
            console.log(usernameRef);

            useEffect( () => {
                // 초기 화면 랜더링 후 출력확인
                console.log(usernameRef);
                // 포커스 설정
                usernameRef.current.focus();
            }, []);



            const onChageHandler = (e) => {
                setForm({
                    ...form,
                    [e.target.name] : e.target.value
                });
            }

            return (
                <>
                    <input 
                        type="text"
                        name="username"
                        ref={ usernameRef }
                        placeholder="username"
                        value={ form.username }
                        onChageHandler={ onChageHandler }
                    />
                    <br/>
                    <input
                        type="password"
                        name="password"
                        placeholder="password"
                        value={ form.password }
                        onChageHandler={ onChageHandler }
                    />
                    <br/>
                    <button>로그인</button>
        
                </>

            );
        }

        ReactDOM.createRoot(document.getElementById('root')).render(<LoginComponent/>);

0개의 댓글

관련 채용 정보