| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 동적객체
- slickslider
- 이미지반응형
- npm install
- 웹아이콘
- package.json
- 그누보드반응형
- googleicon
- 의존성문제
- XEIcon
- maxwidth
- fontawesome
- 글자들여쓰기
- window 정책변경
- npm install 문제
- 단어단위로떨어지기
- legacy-peer
- node 오류
- minwidth
- 아이콘사용법
- react npm install
- Git clone
- node설치
- npm start
- vscode git clone
- 정적객체
- git lab clone
- MediaQuery
- owlcarousel
- 플러그인
- Today
- Total
어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ
[React] useRef(), ref, forwardRef() 본문

✔ useRef()
=> ref 객체를 생성하는 훅
const myRef = useRef();
=> myRef { current: null } 이런 식의 객체를 만들어 줌
=> .current로 직접 접근 가능
<input ref={myRef} />
=> myRef.current는 input DOM을 가리키게 됨
** DOM: 브라우저가 화면에 그리는 실제 HTML 요소
👉 즉 화면에 뿌려진 해당 input을 뜻함
myRef.current === input
ex) myRef.current.focus() 가능
✔ forwardRef()
=> 컴포넌트를 받아서 → ref를 처리해주는 새 컴포넌트를 반환
=> 자식 컴포넌트가 부모에게 받은 ref를 쓸 수 있게 해주는 HOC
** HOC란?
=> 고차 컴포넌트 (Higher-Order Component)
=> 컴포넌트를 인자로 받아서, 새로운 컴포넌트를 반환하는 함수
고차 컴포넌트 예시) 👇
// 원래 컴포넌트
const Hello = ({ name }) => <h1>Hello, {name}!</h1>;
// HOC
const withLogging = (WrappedComponent) => {
return (props) => {
console.log('렌더링 됨!');
return <WrappedComponent {...props} />;
};
};
// HOC로 감싼 새 컴포넌트
const HelloWithLog = withLogging(Hello);
// 사용 (부모 컴포넌트 역할)
const App = () => {
return <HelloWithLog name="React" />;
};

👩🏻 ** 정리
- withLogging: 원래 있던 컴포넌트에 props 연결을 위해 감싸주는 역할
- WrapperComponent: 원래 있던 컴포넌트
- HelloWithLog: 새 컴포넌트
forwardRef() 예시 👇
const MyComponent = forwardRef((props, ref) => {
return <input ref={ref} />;
});
=> 일반 컴포넌트는 ref를 props처럼 못 받기 때문에 가능하게 하기 위래 컴포넌트를 감싸주는 역할을 forwardRef()가 하게 되며, HOC(고차 컴포넌트) 형태로 만든 것
- 부모 -> 자식 컴포넌트에서 ref 쓰는 예시)
✅ 부모 컴포넌트
const Parent = () => {
const inputRef = useRef(); // 🔹 ref 객체 생성
const focusInput = () => {
inputRef.current.focus(); // 🔸 연결된 DOM에 직접 접근
};
return (
<>
<ChildInput ref={inputRef} /> {/* 🔸 ref 전달 */}
<button onClick={focusInput}>Focus the input</button>
</>
);
};
✅ 자식 컴포넌트
const ChildInput = forwardRef((props, ref) => {
return <input ref={ref} />;
});
📚 결론 📚
useRef()로 ref 객체 만든다 → ref={...}로 자식에게 전달한다 → forwardRef()로 받은 자식이 내부에서 쓴다
'개발 > 🟦 React' 카테고리의 다른 글
| [React] useFormik, Formik, 폼 요소에서 쓰이는 라이브러리 (0) | 2025.04.12 |
|---|---|
| [React] 기본 로딩(import), 지연 로딩(lazy) (0) | 2025.04.11 |
| [React] useFormik() 훅 (1) | 2025.04.10 |
| 🟦 [React] && 연산자 / React에서 if 문 대신 && 연산자 사용하기 (0) | 2025.04.01 |
| [Node.js] windows에서 처음 사용할 때 발생하는 문제/ 실행 정책 변경 명령어 입력 (1) | 2025.03.30 |
