개발자 준의 기술블로그


  • 홈

  • 아카이브

  • 태그

  • 검색

삼성전자 입사지원서 이수교과목 매크로

작성일 2021-03-16 | In Any

중요!

더 읽어보기 »

[Redux] Redux under the hood 리덕스 작동원리

작성일 2021-03-14 | In Frontend

작동순서

  1. Create and dispatch actions based on the event
  2. Reducers process the actions, computing the new state
  3. The new state of the whole application goes into a single store
  4. Components receive the new state as props and re-render themselves where needed
더 읽어보기 »

[Interview] Operating System 운영체제

작성일 2021-03-09 | In Coding-test

PCB: 각 process별로 다른 정보를 모아두는 repository

  • process ID
  • process state
  • Program Counter
  • Register value
  • 등

TCB: 각 thread별로 다른 정보를 모아둠

  • TID
  • PC
  • Registers
  • pointer to PCB

Context switch는 현재 돌고 있는 Process/Thread의 정보(State)를 PCB/TCB에 저장하고 바꿀 Process/Thread의 PCB/TCB 정보를 로드하는 과정이기 때문에 저장하는 정보가 적은 Thread의 오버헤드가 훨씬 적다.

Multithreading을 하면 하나의 thread가 I/O에 의해 blocking되었을 때 switching을 해줌으로써 더 높은 throughput을 낼 수 있다(concurrency)

Zombie process: 작업이 끝났지만 parent에 의해 아직 wait()되지 않은 proess
Orphan process: Parent가 wait()을 하기전에 죽어버린 process

  • 주로 init process가 parent로 re-assign되어 wait()해준다.

Scheduler의 종류

  • Long-term Scheduler(Job Scheduler): Disk에 있는 job중 어떤 job을 메모리로 가지고 올지
  • Short-term Scheduler(CPU Scheduler): Memory에 있는 job중 어떤 job에게 CPU를 할당해줄지
  • Mid-term Scheduler: 메모리가 부족할 때 잠시 어떤 job을 Disk로 swapping할지

Scheduling Queue 종류

  • Job queue: set of all processes in the system
  • Ready queue: set of all processes in main memory, ready and waiting to execute
  • Device queue: set of processes waiting for an I/O device

Scheduling 방법

  • Shortest Job first
  • FCFS
    • Convoy effect: 들어온 순서대로 처리되므로 앞쪽에 느린 process가 들어오면서 전체 process의 wait time이 길어지는 현상
  • Priority
  • RoundRobin

Race condition: 어떤 process가 먼저 작업을 마치느냐에 따라 결과가 달라지는 것
Critical section: shared data에 access하는 code
Atomic operation: 외부의 방해없이(switching없이) 끝까지 실행하는 operation

Synchronization 방법

  • Mutex Lock: lock(), unlock() 한번에 하나의 process/thread가 접근가능
  • Semaphore: wait(), signal() 한번에 허용한 갯수의 process/thread가 접근가능
  • Spinlock: busy-waiting - mutex는 thread를 sleep/wake하는 overhead가 있기때문에 잠깐만 기다리는 경우 spinlock이 더 효율적일 수 있다.

Starvation: process의 처리 순서가 밀려 계속 처리되지 못하고 기다리는 현상
Deadlock: 내가 필요한 resource를 다른 process가 가지고 있어 더이상 진행이 불가능한 상황

Deadlock 발생조건

  • 상호배제(Mutual exclusion): 동시에 여러 프로세스가 하나의 자원을 access할 수 없다
  • 점유대기(Hold and wait): 최소한 하나의 자원을 점유하고 있으면서 다른 프로세스이 할당되어 사용하고 있는 자원을 추가로 점유하기 위해 대기하는 프로세스가 있어야한다
  • 비선점 (No preemption): 다른 프로세스에 할당된 자원은 사용이 끝날때까지 강제로 빼앗을 수 없어야 한다.
  • 순환대기 (Circular Wait): 각 프로세스는 순환적으로 서로가 점유한 자원을 요구해야하낟.

Deadlock 예방법(prevention): 위 4가지 조건을 부정. 하나만 제거해도 됨
Deadlock 회피법(avoidance): 교착 상태가 발생하면 피해나가는 방법
은행원 알고리즘:

  • 알고리즘이 제대로 수행되기 위해서는 3가지가 필요하다
    1. 각 고객이 요구할 수 있는 Maximum 돈
    2. 각 고객이 빌려간 돈이 얼마인지 (Allocated)
    3. 은행이 현재 남아있는 돈이 얼마인지 (Available)
  • 안전 상태: 시스템이 교착상태를 일으키지 않으면서 각 프로세스가 요구한 최대 요구량만큼 필요한 자원을 할당해줄 수 있는 안전순서열이 있는 상태
    • 어떠한 프로세스1(P1)에게 남아있는 리소스를 빌려주면 P1이 완료되어 반환된 자원으로 다음 프로세스를 완료시켜 모든 프로세스를 만족시킬 수 있는 것
  • 불안전 상태: 안전순서열이 존재하지 않는 상태 https://jhnyang.tistory.com/102

External Fragmentation: memory가 process가 요구한 만큼 비어있지만 연속되지 않아 사용하지 못하는 경우
Internal Fragmentation: process가 request한 memory보다 더 큰 메모리를 할당받아서 남는 메모리

Paging: Logical memory를 page들로 나누고, physical memory를 page와 같은 사이즈의 frame들로 나눔. Page table을 사용하여 logical address를 physical address로 변환한다.

  • Page number로 page table에서 base physical address를 찾고, 거기에 page offset을 더해 실제 physical address를 구한다

Segmentation: segment(main program/function/object/var 등)별로 저장을 하고 logical address를 <segment # / offset >으로 나누어 segment table에서 segment #로 검색을 하여 limit(length)와 base를 가져온다. segment는 base + offset ~ base + offset + limit에 있음.

Copy-On-Write: 일반적인 fork()는 process를 생성하고, 메모리를 복사하고, exec()을 통해 덮어씌우는데 overhead가 크다. 따라서 새로 process를 만들때, page table만 만들고 같은 page를 가리키다가, 만약 어떤 process가 page를 수정하면 수정하는 process가 page를 다른 곳으로 복사하고 복사된 frame을 수정하고 그 frame을 가리킨다.

Demand Paging: execution 중에 page가 필요하면 load함

Page Replacement Methods\

  • FIFO
  • Optimal Algorithm
  • LRU
    • Counter implementation: Memory access마다 clock을 증가시키고, access된 page의 page table entry의 clock을 업데이트. 가장 작은 값이 LRU page이다.
    • Stack Implementation: Page가 reference되면 stack의 가장 위로 올린다.
  • LRU Approximation
    • Reference Bit Algo: HW가 관리하는 reference bit을 두고 reference되면 1
    • Referene Byte Algo: 위의 reference bit algorthm은 참조된 순서나 횟수는 알 수 없으므로, 8비트짜리 reference byte를 놔두고 주기마다 reference bit을 기록하고 오른쪽으로 shift한다. 최근에 access되면 더 높은 bit가 1이므로 unsgined int기준으로 더 큰 숫자가 된다.
    • Second Chance Algo: 처음에 page의 reference bit들을 1로 세팅하고 fault가 발생하면 victim pointer부터 순회하며 1이면 0으로 바꾸고 0이면 replace.
  • LFU
  • MFU

Thrashing: A process is spending more time swapping pages in and out than executing because process didn’t get enough frames

FCB: information about files
Directory: 각 파일의 FCB를 관리하는 구조로서 파일이름과 FCB를 가리키는 포인터로 이루어짐

Windows FS(File-Allocation Table):

  • 실제 data는 Data Area의 block/cluster에 저장하고 다음 block의 위치는 FAT에서 찾는다.
  • directory에서 첫 block index(a)를 가지고 있고 FAT에서 a번째 index를 접근하면 block a 다음이 있다면 index, 없으면 EOF를 가지고 있다.

Unix FS(i-node):

  • directory가 file name과 pointer를 가지고 있어 i-node(FCB)를 가리키고 있으며, i-node에는 file의 attribute들과 함께 direct block, single indirect, double indirect, triple indrect 포인터들을 가지고 있다.
더 읽어보기 »

[Coding Test] Javascript stack, queue, heap

작성일 2021-03-06 | In Coding-test

Stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Stack {
  constructor() {
    this._arr = [];
  }
  push(item) {
    this._arr.push(item);
  }
  pop() {
    return this._arr.pop();
  }
  peek() {
    return this._arr[this._arr.length - 1];
  }
}

const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop(); // 3

Queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Queue {
  constructor() {
    this._arr = [];
  }
  enqueue(item) {
    this._arr.push(item);
  }
  dequeue() {
    return this._arr.shift();
  }
}

const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.dequeue(); // 1

Heap (조금 더 범용성있게 수정)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class BinaryHeap {
  constructor() {
    this.heap = [];
    this.key ='';
    this.count = 0;
  }

  insert(value) {
    this.heap.push(value);
    this.bubbleUp();
    this.count++
  }
    
  getValue(obj){
      if (this.key == '') return obj
      return obj[this.key]
  }

  bubbleUp() {
    let currentIndex = this.heap.length - 1;

    while (currentIndex > 0) {
      let current = this.heap[currentIndex];
      let parentIndex = Math.floor((currentIndex - 1) / 2);
      let parent = this.heap[parentIndex];

      if (this.getValue(parent) >= this.getValue(current)) break;
      this.heap[currentIndex] = parent;
      this.heap[parentIndex] = current;
      currentIndex = parentIndex;
    }
  }

  extractMaxValue() {
    if (this.count === 0)
      return null
    const max = this.heap[0];
    this.heap[0] = this.heap.pop();
    this.sinkDown(0);
    this.count--;

    return max;
  }

  sinkDown(index) {
    let left = 2 * index + 1;
    let right = 2 * index + 2;
    let largest = index;
    const length = this.heap.length;

    if (left <= length && this.getValue(this.heap[left]) > this.getValue(this.heap[largest])) {
      largest = left;
    }
    if (right <= length && this.getValue(this.heap[right]) > this.getValue(this.heap[largest])) {
      largest = right;
    }
    // swap
    if (largest !== index) {
      [this.heap[index], this.heap[largest]] = [
        this.heap[largest],
        this.heap[index],
      ];

      this.sinkDown(largest);
    }
  }
}

const heap = new BinaryHeap()
heap.insert(5)
heap.insert(3)
console.log(heap.extractMaxValue())
console.log(heap.extractMaxValue())
console.log(heap.extractMaxValue())

Reference:
https://helloworldjavascript.net/pages/282-data-structures.html
https://jeongw00.tistory.com/172

더 읽어보기 »

[Coding Test] Javascript nested sort

작성일 2021-03-06 | In Coding-test
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const ASCENDING = 1
const DESCENDING = -1
const dir = DESCENDING
const priority = ['a','b']
const sortFunc = (a,b) => {
  for (let i=0; i<priority.length; i++){
    if (a[priority[i]] > b[priority[i]])
      return dir
    else if (a[priority[i]] < b[priority[i]])
      return -dir
  }
  return 0
}

const arr = [{a: 3, b: 4}, {a: 1, b: 2}, {a: 3, b: 2}]
arr.sort(sortFunc)
console.log(arr)

dir과 priority만 바꿔서 쓰면된다.

더 읽어보기 »

[Interview] React Fiber

작성일 2021-02-27 | In Interview

React Fiber

React 15.x는 Stack이라고 부르며 React 16.x는 Fiber라고 부릅니다.

Fiber is a new reconciliation engine or reimplementation of core algorithm in React v16. The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, etc.

What is Reconciliation

When React encounters a class or a function component, it will ask that element what element it renders. React will call render() to know what elements it renders. React will repeat this process until it knows the underlying DOM tag elements for every component on the page. By the end of reconciliation, React knows the result of DOM tree and renderer like react-dom applies the minimal set of changes necessary to update the DOM nodes.

Problems of Stack reconciliation

The reconciliation algorithm we just saw is a purely recursive algorithm. An update results in the entire subtree being re-rendered immediately. While this works well, this has some limitations. As Andrew Clark notes:

  • In a UI, it’s not necessary for every update to be applied immediately; in fact, doing so can be wasteful, causing frames to drop and degrading the user experience
  • Different types of updates have different priorities — an animation update needs to complete more quickly than, say, an update from a data store

Most devices refresh their screens at 60FPS(every 16.67ms). So if React renderer takes more than 16ms to render something on the screen, browser will drop that frame. So if the React reconciliation algorithm traverses the entire App tree each time there is an update and re-renders it, and if that traversal takes more than 16ms, it will cause dropped frames, and dropped frames are bad.

If you rely only on the built-in call stack, it will keep doing work until the stack is empty. So to solve this problem, React had to re-implement the algorithm for walking the tree from the synchronous recursive model that relied on the built-in stack to an asynchronous model with linked list and pointers.

Stack reconciliation처럼 synchronous하게 매번 Tree를 recursive하게 타고 들어가서 맨 하단까지 살펴보지 않는 이상 어떻게 render를 해야되는지 알 수 없고, 이렇게 되면 16ms를 넘을 수도 있다.

React Fiber

모든 React Element는 각자의 Fiber node를 가지고 있다.

Features:

  • Assign priority to different types of work
  • Pause work and come back to it later
  • Abort work if it’s no longer needed
  • Reuse previously completed work

In simple terms, a fiber represents a unit of work with its own virtual stack. In the previous implementation of the reconciliation algorithm, React created a tree of objects (React elements) that are immutable and traversed the tree recursively.

In the current implementation, React creates a tree of fiber nodes that can be mutated. The fiber node effectively holds the component’s state, props, and the underlying DOM element it renders to.

And since fiber nodes can be mutated, React doesn’t need to recreate every node for updates — it can simply clone and update the node when there is an update. Also, in the case of a fiber tree, React doesn’t do a recursive traversal; instead, it creates a singly linked list and does a parent-first, depth-first traversal.

처음에는 createFiberFromTypeAndProps()를 사용하여 Fiber node를 생성하고 그 뒤부터는 변경된 부분만 update한다.

linked-list를 사용하는 방식으로 변경하였더니 render phase를 asynchronous하게 작업을 처리할 수 있게 되었다.
render phase는 user-visible한 change를 야기하지는 않기때문에 잠시 멈췄다 이어서 작업하는 등 async하게 가능하다.

하지만 commit phase는 실제로 DOM update를 진행하기 때문에 synchronouse하게 single pass에 작업한다.

Once the render phase completes, React moves on to the commit phase, where it basically swaps the root pointers of the current tree and workInProgress tree. workInProgress 트리는 user에게 보이지 않는 draft역할을 한다.

And what about the 16ms frame time? React effectively runs an internal timer for each unit of work being performed and constantly monitors this time limit while performing the work. The moment the time runs out, React pauses the current unit of work being performed, hands the control back to the main thread, and lets the browser render whatever is finished at that point.

Then, in the next frame, React picks up where it left off and continues building the tree. Then, when it has enough time, it commits the workInProgress tree and completes the render.

Reference:
https://github.com/sudheerj/reactjs-interview-questions#what-is-react-fiber
https://blog.logrocket.com/deep-dive-into-react-fiber-internals/
https://medium.com/@mailabhi555/react-fiber-implementation-vs-stack-implementation-916ef69a707c
https://indepth.dev/posts/1008/inside-fiber-in-depth-overview-of-the-new-reconciliation-algorithm-in-react

더 읽어보기 »

[Interview] React 인터뷰 준비

작성일 2021-02-27 | In Interview

여러 인터뷰 질문 모음들을 보여 애매하게 또는 잘못알고 있던 점들만을 뽑아서 정리하였습니다. 전체 리스트는 하단의 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\

더 읽어보기 »

[React] React Parent와 Child간 method 호출 순서

작성일 2021-02-21 | In Frontend

create order

1
2
3
4
5
6
7
8
9
10
parent constructor
parent WillMount
parent render

child constructor
child WillMount
child render
child DidMount

parent DidMount

destroy order

1
2
3
4
5
6
7
parent WillUnmount

child WillUnmount

// child unmount

// parent unmount

Reference:
https://stackoverflow.com/questions/44654982/in-which-order-are-parent-child-components-rendered

더 읽어보기 »

[React] React Component간 transition을 위한 React-Transition-Group

작성일 2021-02-04 | In Frontend

공식문서 바로가기

React-Transition-Group에는 크게 4가지 컴포넌트가 정의되어있다.

  1. Transition: component간의 transition을 정의하기 위한 component
  2. CSSTransition: CSS간의 transition을 정의하기 위한 component (만약 본인의 CSS에서 transition을 정의하고 있다면 CSSTransition을 사용하라고 한다)
  3. SwitchTransition: State간의 transition을 정의하기 위한 comopnent
  4. TransitionGroup: 위의 3가지 transition 중 여러 transition component를 배열로 한번에 관리할 때 사용한다.

Reference:
https://medium.com/lalilo/dynamic-transitions-with-react-router-and-react-transition-group-69ab795815c9

더 읽어보기 »

[Javascript] Airbnb javascript convention 중 새로알게된 점 정리

작성일 2021-02-03 | In Frontend

원문 바로가기

  • Function declarations are hoisted 링크
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // bad
    function foo() {
      // ...
    }
    
    // bad
    const foo = function () {
      // ...
    };
    
    // good
    // lexical name distinguished from the variable-referenced invocation(s)
    const short = function longUniqueMoreDescriptiveLexicalFoo() {
      // ...
    };
    
  • Put all imports aboue non-imoprt statements because imports are hoisted

  • Avoid using unary increments and decrements (++, --) 링크

  • 그냥 function은 hoisting되며 코드 이전에서 사용될 수 있지만, var에 assign되는 경우 variable name만 hoisting되며 function name, function body는 hoisting되지 않는다. 링크
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // the same is true when the function name
    // is the same as the variable name.
    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      var named = function named() {
        console.log('named');
      };
    }
    
    function example() {
      superPower(); // => Flying
    
      function superPower() {
        console.log('Flying');
      }
    }
    
  • Lexical declaration(let,const,function,and class)이 switch문의 case안에서 사용되는 경우 { }로 감싸주도록 한다 링크

  • Control statement가 너무 길어질 때:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // bad
    if (foo === 123
      && bar === 'abc') {
      thing1();
    }
    
    // bad
    if (
      foo === 123 &&
      bar === 'abc'
    ) {
      thing1();
    }
    
    // good
    if (
      foo === 123
      && bar === 'abc'
    ) {
      thing1();
    }
    
더 읽어보기 »
1 2 … 5
Junsoo Choi

Junsoo Choi

41 포스트
8 카테고리
46 태그
RSS
Github LinkedIn
© 2021 Junsoo Choi
Contact: cjsjyh@gmail.com