본문 바로가기
React.js/Hooks

useRef

by Jinny96 2023. 1. 5.

1. Issue

  • React는 State가 변경될 때마다 렌더링 된다.
  • input 값을 useState로 관리하면 불필요한 리렌더링이 발생한다.
  • 이를 방지하고자 input 값을 useRef로 관리한다.

2. useRef

useRef는 저장공간(변수 관리), DOM 요소에 접근하기 위해 사용되는 React Hooks이다.


3. Refactoring (Before)

// auth.js

import { useState } from "react";

import { Typography, Box, TextField, Button } from "@mui/material";

const Auth = () => {
    const [id, setId] = useState("");
    const [password, setPassword] = useState("");
    
    const onChange = (e) => {
        if (e.target.id === "userId") {
            setId(e.target.value);
        } else {
            setPassword(e.target.value);
        }
    };

    return (
        <Box sx={{ marginTop: 10, display: 'flex', flexDirection: 'column', alignItems: 'center', height: '79vh' }}>
            {console.log("render")}
            <TextField
                id="userId"
                label="ID"
                variant="outlined"
                onChange={onChange}
                sx={{
                    width: 300,
                    mt: 10,
                    "& .MuiOutlinedInput-root": { "& > fieldset": { borderColor: "#d3d3d3" } },
                    "& .MuiOutlinedInput-root.Mui-focused": { "& > fieldset": { borderColor: "black" } },
                    "& .MuiOutlinedInput-root:hover": { "& > fieldset": { borderColor: "black" } }
                }}
            />
            <TextField
                id="userPassword"
                label="Password"
                type="password"
                variant="outlined"
                onChange={onChange}
                sx={{
                    width: 300,
                    mt: 2,
                    "& .MuiOutlinedInput-root": { "& > fieldset": { borderColor: "#d3d3d3" } },
                    "& .MuiOutlinedInput-root.Mui-focused": { "& > fieldset": { borderColor: "black" } },
                    "& .MuiOutlinedInput-root:hover": { "& > fieldset": { borderColor: "black" } }
                }}
            />
        </Box>
    )
}

export default Auth;

첫 렌더링 이후 아이디와 비밀번호 값이 바뀔 때마다 렌더링 되고 있다.


4. Refactoring (After)

import { useRef } from "react";

import { Typography, Box, TextField, Button } from "@mui/material";

const Auth = () => {
    const idRef = useRef(null);
    const passwordRef = useRef(null);
    
    const onChange = (e) => {
        if (e.target.id === "userId") {
            idRef.current = e.target.value;
        } else {
            passwordRef.current = e.target.value;
        }
    };
    
    return (
        <Box sx={{ marginTop: 10, display: 'flex', flexDirection: 'column', alignItems: 'center', height: '79vh' }}>
            {console.log("render")}
            <TextField
                ref={idRef}
                id="userId"
                label="ID"
                variant="outlined"
                onChange={onChange}
                sx={{
                    width: 300,
                    mt: 10,
                    "& .MuiOutlinedInput-root": { "& > fieldset": { borderColor: "#d3d3d3" } },
                    "& .MuiOutlinedInput-root.Mui-focused": { "& > fieldset": { borderColor: "black" } },
                    "& .MuiOutlinedInput-root:hover": { "& > fieldset": { borderColor: "black" } }
                }}
            />
            <TextField
                ref={passwordRef}
                id="userPassword"
                label="Password"
                type="password"
                variant="outlined"
                onChange={onChange}
                sx={{
                    width: 300,
                    mt: 2,
                    "& .MuiOutlinedInput-root": { "& > fieldset": { borderColor: "#d3d3d3" } },
                    "& .MuiOutlinedInput-root.Mui-focused": { "& > fieldset": { borderColor: "black" } },
                    "& .MuiOutlinedInput-root:hover": { "& > fieldset": { borderColor: "black" } }
                }}
            />
        </Box>
    )
}

export default Auth;

useRef로 아이디와 비밀번호를 관리하여 불필요한 렌더링을 방지했다.

'React.js > Hooks' 카테고리의 다른 글

useState  (0) 2024.02.13
useEffect  (1) 2024.01.27

댓글