[ React ] 리액트 공식 문서 - Context, Ref 전달, Fragment

혱·2023년 8월 17일

Context

props를 하나하나 넘겨주지 않고 컴포넌트 트리 전체에서 데이터를 제공
전역적인 데이터를 공유할 수 있도록 고안된 방법

예시로 살펴보자

const ThemeContext = React.createContext('light');

class App extens React.Component {
  render() {
    return(
      <ThemeContext.Provider value='dark'>
      	<Toolbar/>
      </ThemeContext.Provider>
      );
  }
}

API

React.createContext

const MyContext = React.createContext(defaultValue);

Context 객체를 만들고, 이를 구독하고 있는 컴포넌트를 렌더링할 때 React는 트리 상위에서 가장 가까이 있고 짝이 맞는 Provider로부터 현재값을 읽음
defaultValue 는 적절한 Provider를 찾지 못했을 때만 쓰임

Context.Provider

<MyContext.Provider value={~~}>

Context를 구독하는 컴포넌트들에게 Context의 변화를 알리는 역할
value prop을 받아 하위 컴포넌트에 전달함
따라서 전달받은 컴포넌트는 value 가 바뀔 때마다 재렌더링이 이루어짐

Context.Consumer

<MyContext.Consumer>
	{value => context갑승ㄹ 이용한 렌더링 }
</MyContext.Consumer>

Context를 구독하는 컴포넌트로, 함수 컴포넌트 안에서 context구독 가능
Context.Consumer의 자식은 함수여야 하며 이는 context의 현재값을 받고 React Node 반환

Ref 전달

일부 컴포넌트가 수신한 ref를 받아 조금 더 아래로 전달할 수 있는 기능

예시로 살펴보자

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className='FancyButton'>
                                     {props.children}
</button>
));

const ref = React.createRef();
<FancyButton ref={ref}>Click Me! </FancyButton>
  1. React.createRef 호출로 Reac ref 생성, ref 변수에 할당
  2. ref를 JSX 속성으로 지정, <FancyButton ref={ref}> 로 전달
  3. 해당 ref를 forwardRef 내부의 (props, ref) 함수의 두번째 인자로 전달
  4. 이 ref는 <button ref 로 전달됨
  5. ref.current는 <button> 노드를 가리키게 됨

Fragments

DOM에 별도의 노드를 추가하지 않고 여러 자식을 그룹화

예시로 살펴보자

render(){
  return(
    <React.Fragment>
    	<ChildA/>
    	<ChildB/>
    </React.Fragment>
    );
}
  • <> </> 빈 태그로 짧게 형성할 수도 있다
profile
new blog: https://hae0-02ni.tistory.com/

0개의 댓글