[Interview] React 인터뷰 준비

여러 인터뷰 질문 모음들을 보여 애매하게 또는 잘못알고 있던 점들만을 뽑아서 정리하였습니다. 전체 리스트는 하단의 Reference를 참고해주세요

What is the difference between Element and Component

An element is a plain object describing a component instance or DOM node and its desired properties. In other words, elements are not actual DOM nodes or component instances; they are a way to describe to React what kind of elements they are, what properties they hold, and who their children are.\

Component can be declared in several ways and returns a JSX tree as the output. Then JSX gets transpiled to a React.createElement().\

Functional component declaration vs expression (TS)

Typescript를 사용할 때 function expression으로 component를 선언하면

1
const Greetings: React.FC<GreetingsProps> = ({ name }) => ();

이렇게 선언하게되는데 React.FC는 기본적으로 children props를 가지고 있기때문에 명시적으로 무조건 가져야되는 경우나 가지지 말아야되는 경우를 표현할 때 힘들다. 추가로 defaultProps가 정상적으로 작동하지 않는다.\

https://velog.io/@velopert/create-typescript-react-component\

What are Pure Components?

Class component를 사용하면 shouldComponentUpdate()는 별도의 처리를 하지 않을 경우 항상 true를 반환하기때문에 props나 state의 값이 변하지 않더라도 re-render된다. 하지만 React.PureComponet로 선언할 경우 shallow comparison을 하여 setState()등이 호출되더라도 props와 state가 변하지 않았다면 re-render하지 않는다.\

What are synthetic events in React?

SyntheticEvent is a cross-browser wrapper around the browser’s native event. It’s API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.\

useRef vs createRef

createRef()는 항상 새로운 ref를 생성하여 반환한다. 따라서 class-based component에서는 constructor에 넣어 사용한다. 하지만 function component에는 생성자가 없기때문에 createRef()를 사용하면 매 렌더링마다 새로운 ref가 생성된다. useRef()는 initial rendering이후부터는 같은 ref를 반환한다.\

https://stackoverflow.com/questions/54620698/whats-the-difference-between-useref-and-createref\

Shadow DOM vs Virtual DOM

Virtual DOM은 라이브러리 차원에서 browser API를 사용하여 구현한 concept이다.
Shadow DOM은 DOM의 구조를 캡슐화할 때 사용한되며 웹 컴포넌트 중 하나이다.\

특징:

  • 외부의 style은 적용되지 않는다. 또 내부의 style이 밖에 영향을 미치지도 않는다.
  • Shadow DOM외부와 같은 id, class를 사용할 수 있다.
  • Shadow DOM을 추가하거나 접근하기 위해서는 별도의 방법이 필요하다

https://d2.naver.com/helloworld/188655
https://kyu.io/%EC%9B%B9-%EC%BB%B4%ED%8F%AC%EB%84%8C%ED%8A%B83%E2%80%8A-%E2%80%8A%EC%89%90%EB%8F%84%EC%9A%B0-%EB%8F%94shadow-dom/

What is uncontrolled components?

React에서 state나 props로 값을 관리하는 것이 아니라 HTML element 자체에서 값을 가지고 ref를 통해 필요할 때 값을 가져다 쓰는 것

What are Higher-Order Components?

A higher-order component (HOC) is a function that takes a component and returns a new component.

React Fragments

React는 class component의 render()나 function component의 return()에서 복수의 element를 반환하는 것을 허용하지 않는다. React Fragment를 사용하면 별도의 노드를 사용하지 않고 grouping하여 반환할 수 있다

1
2
3
4
5
6
return (
  <>
    <Child A/>
    <Child B/>
  </>
)
  • DOM node를 사용하지 않기 때문에 조금이나마 적은 메모리를 사용한다
  • 로 wrapping할 경우 flexbox나 grid를 사용할 때 css를 다시 정의해줘야되는 것을 방지
  • DOM inspector가 넘치지 않는다.

Why we need to pass a function to setState()?

The reason behind for this is that setState() is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after setState() is called. By passing a function that uses prevState and props you can overcome this problem.

What is the difference between super() and super(props) in Class-based component?

super()로 하게되면 constructor안에서 this.props를 사용할 수 없다. 하지만 constructor밖에서는 두 경우 모두 this.props를 동일하게 사용할 수 있다.

JSX안에서 statements(if, for 등)을 사용하지 못하는 이유

JSX은 function call과 object construction을 위한 syntactic sugar이기 때문에 사용할 수 없다.

1
2
3
4
ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);

// Is transformed to this JS:
ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);
1
2
3
4
5
// This JSX:
<div id={if (condition) { 'msg' }}>Hello World!</div>

// Is transformed to this JS:
React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");

https://react-cn.github.io/react/tips/if-else-in-JSX.html

What are render props?

Render Props is a simple technique for sharing code between components using a prop whose value is a function. The below component uses render prop which returns a React element.

정리하자면, render prop은 무엇을 렌더링할지 컴포넌트에 알려주는 함수입니다.

https://ko.reactjs.org/docs/render-props.html

How JSX prevents injection Attacks?

React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered.

React’s diffing algorithm

React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree. The diffing algorithms is generating the minimum number of operations to transform one tree into another. However, the algorithms have a complexity in the order of O(n^3) where n is the number of elements in the tree.

In this case, for displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm under 2 assumptions.

  1. 서로 다른 타입의 두 엘리먼트는 서로 다른 트리를 만들어낸다.
  2. 개발자가 key prop을 통해, 여러 렌더링 사이에서 어떤 자식 엘리먼트가 변경되지 않아야 할지 표시해 줄 수 있다.

Rules:

  1. Elements Of Different Types: Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. For example, elements to , or from to of different types lead a full rebuild.
  2. DOM Elements of the same type: React looks at the attributes of both, keeps the same attributes and only updates the changed attributes.
  3. Component Elements Of The Same Type: 컴포넌트가 갱신되면 인스턴스는 동일하게 유지되어 렌더링 간 state가 유지됩니다. React는 새로운 엘리먼트의 내용을 반영하기 위해 현재 컴포넌트 인스턴스의 props를 갱신합니다. 그 다음 render()가 호출되며 변경된 props를 반영하고 diffing 알고리즘이 이전 결과와 새로운 결과를 재귀적으로 처리합니다.
  4. Handling keys: 자식들을 비교할 때 key를 확인하여 추가나 이동을 시킵니다. key를 사용하지 않는다면 순차적으로 내용을 비교하며 ```js
  • Duke
  • Villanova
  • Connecticut
  • Duke
  • Villanova

``` 에서 Duke와 Villanova가 아래로 이동했다는 사실을 알 수없기 때문에 폐기하고 다시 처음부터 새로 만들어야됩니다.

https://ko.reactjs.org/docs/reconciliation.html

What is the typical use case of portals?

React portals are very useful when a parent component has overflow: hidden or has properties that affect the stacking context(z-index,position,opacity etc styles) and you need to visually “break out” of its container.

For example, dialogs, global message notifications, hovercards, and tooltips.

Is Hooks cover all use cases for classes?

Hooks doesn’t cover all use cases of classes but there is a plan to add them soon. Currently there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet.

Reference:
https://github.com/sudheerj/reactjs-interview-questions\