-
부모컴포넌트에게 정보를 전달해줄 수 있는 forwardRefReact 2023. 1. 11. 22:24
나와 같이 리액트에 입문한지 얼마 안된 사람들이라면 아래와 같은 상황을 맞닥뜨린적이 있었을 것이다.
function App() { return ( <div> <Children /> </div> ); } function Children() { return ( <div> <button>Close</button> </div> ); }
App 컴포넌트는 Children이라는 컴포넌트를 갖고있다.
자식 컴포넌트(Children 컴포넌트)에서 Close 버튼을 클릭하면 App 컴포넌트에서 Children 컴포넌트가 사라져야 하는 상황이다.
나는 이런상황에서 forwardRef를 알기전까지는 부모 컴포넌트에서 자식컴포넌트의 state를 관리하는 식으로 진행하였다.
function App() { const [child,setChild] = useState(true); const callback = (isOn) => { setChild(isOn); } return ( <div> {child && <Children callback={callback}/>} </div> ); } function Children({callback}) { const isOn = () => { callback(false); } return ( <div> <button onClick={isOn}>Close</button> </div> ); }
이런식으로 부모 컴포넌트에서 자식 컴포넌트의 상태를 관리하는 useState를 갖고, 콜백을 자식 컴포넌트에 전달하여 자식 컴포넌트는 전달받은 콜백에 값을 전달하는 방식으로 진행하였다.
어떻게 보면 매우 비효율적이라고 할 수 있다.
그러한 이유는 콜백을 전달하기 때문에 구조가 복잡해지게 되고, 자식 컴포넌트의 상태를 부모 컴포넌트가 관리하는 것 또한 이상하게 보일 수 있다.
그래서 이때 forwardRef라는 것을 사용하면 자식 컴포넌트의 상태를 부모 컴포넌트에서 관리할 수 있게 된다.
function App() { const isOpen = useRef({}); isOpen.current.isOn(); return ( <div> <Children isOpen={isOpen} /> </div> ); } const Children = forwardRef((props, ref) => { const [open, setOpen] = useState(true); const isOn = () => { setOpen(false); }; useImperativeHandle(ref, () => { return { isOn: isOn }; }); return ( <div> {open && <h1 onClick={isOn}>Close</h1>} </div> ); });
ㅋ이렇게 forwardRef를 사용함으로써 부모 컴포넌트에서 자식 컴포넌트로만 데이터를 전송하는 단방향 흐름에서 자식 컴포넌트의 데이터를 부모 컴포넌트에서도 사용할 수 있게 된다.
'React' 카테고리의 다른 글
[PropTypes] 리액트에서 타입 검사를 해보자! (0) 2022.08.25