1. React.Fragment (<></>)
추가 HTML 요소 없이 여러 요소를 함께 렌더링하려는 경우에 사용한다.
react legacy docs의 JSX in Depth 파트를 보면 JSX는 React.createElement의 syntatic sugar임을 상기해 보면 왜 그루핑이 필요한 지 알 수 있다.
import React from 'react';
import CustomButton from './CustomButton';
function WarningButton() {
// return React.createElement(CustomButton, {color: 'red'}, null);
return <CustomButton color="red" />;
}
// node_modules/@types/react/index.d.ts
function createElement<P extends {}>(
type: FunctionComponent<P> | ComponentClass<P> | string,
props?: Attributes & P | null,
...children: ReactNode[]): ReactElement<P>;
2. return null
정말 비어 있어서 아무것도 렌더링하지 않으려는 경우에 사용한다.
React의 소스 코드에서 empty component를 체크하는 테스트 코드에서도 null을 사용하고 있다.
describe('ReactEmptyComponent', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
findDOMNode =
ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE
.findDOMNode;
ReactDOMClient = require('react-dom/client');
Scheduler = require('scheduler');
const InternalTestUtils = require('internal-test-utils');
act = InternalTestUtils.act;
assertLog = InternalTestUtils.assertLog;
container = document.createElement('div');
TogglingComponent = class extends React.Component {
state = {component: this.props.firstComponent};
componentDidMount() {
Scheduler.log('mount ' + findDOMNode(this)?.nodeName);
this.setState({component: this.props.secondComponent});
}
componentDidUpdate() {
Scheduler.log('update ' + findDOMNode(this)?.nodeName);
}
render() {
const Component = this.state.component;
return Component ? <Component /> : null;
}
};
});
3. return false
null을 반환하는 것과 마찬가지로 컴포넌트가 DOM에서 아무 것도 렌더링하지 않는다.
차이점은 false를 반환하면 컴포넌트가 향후 업데이트되지 않는다. React는 false를 컴포넌트를 마운트를 해제하라는 신호로 해석하기 때문에 의도하지 않은 결과를 초래할 수 있다.
📚 참고 자료
Understanding “return null” vs “return false” in React
Hello everyone. This week in #SundayTechMusings, I will try to explain the difference between “return null” and “return false” in React.
tech.jotform.com
React Fragment vs Null - 정현수 기술 블로그
React Fragment와 return null의 차이점
junghyeonsu.com
Conditional rendering 에서 empty component는 어떻게 처리할까?
처음 든 생각은 Fragment를 이용하는 방법이였다. 반환값으로 를 제공하면, React스럽게 진행될것이라 예상하였다. 이전에 다른 분이 짜놓으신 코드에서는 상황별로 component가 를 반환하게끔 처리
sukjae.github.io
dev-blog/JavaScript/return-null-vs-undefined.md at master · yeonjuan/dev-blog
개발 블로그, 공부한거 정리. Contribute to yeonjuan/dev-blog development by creating an account on GitHub.
github.com
'배워서 남 주자' 카테고리의 다른 글
Next.js 14의 API Layer : 클라이언트 컴포넌트에서 Route Handlers를 fetch하는 방법 (0) | 2024.05.12 |
---|---|
상세 페이지에서 뒤로가기 클릭시 원래 있던 목록 페이지로 돌아가기 (0) | 2024.04.23 |
tanstack react-virtual을 사용하여 무한 스크롤 성능 최적화 하기 (1) | 2024.03.24 |
디자인 패턴 - Command 패턴 (0) | 2024.01.22 |
디자인 패턴 - Mediator/Middleware 패턴 (0) | 2024.01.08 |