React + TS
DALI
Vol1.

다들 좋다하니
Refactoring 1.
START




&
&
1. React & Vue 비교
2. React TS 공부한 부분 (Interface, Generic, with emotion)


&
1. React & Vue 비교


장점: 진입하기 용이하다
- 문법이 framework 처음 접하는 사람한테 더 쉽다.
+ directive eventModifier등 편의기능들
-> + styleguide + extension !!!
장점: 좀 까다라운 대신 더 좋은 DX 제공 +
7:3 -> 생태계 + 발전속도 파워
단점: 진입하기 좀 더 까다롭다

SingleFileComponent
directive -> v-if, methods.stop
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
import React from "react";
import "./styles.css";
const Hello = ({ msg }) => <h1> {msg}</h1>;
const Person = ({ person }) => <h1> {person}</h1>;
export default function App() {
return (
<div className="App">
<Hello msg="hi" />
<Person person="dali" />
</div>
);
}

컴포넌트 등록 필요 없음
한 파일에 간단한 컴포넌트 여러개 작성
Vue option Object 상대적으로 번거로움
props , components등 일일이 적어주어야 함

2018 Hooks vs 2020 Vue 3.0 composition 아직 릴리즈..
생태계 빠른 발전 vercel -> next ,swr,
facebook -> reconcil
Reactivity Render 비교

Reactivity Render 비교
Vue


Reactivity Render 비교
React
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
Component.prototype.setState = function(partialState, callback) {
invariant(
typeof partialState === 'object' ||
typeof partialState === 'function' ||
partialState == null,
'setState(...): takes an object of state variables to update or a ' +
'function which returns an object of state variables.',
);
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};


&
2. React TS 공부한 부분 (Interface, Generic, with emotion)
❯ yarn create react-app my-app --template typescript


&
2. React TS 공부한 부분 (Interface, Generic, with emotion)
const person = 'dali';
const person2:string = 'dali2';
let number = 3;
number = '2'



&
2. React TS 공부한 부분 (Interface, Generic, with emotion)
function sum(x: number, y: number): number {
return x + y;
}
sum(1, 2);
function total(numbers: number[]): number {
return numbers.reduce((acc, cur) => acc + cur, 0)
}
function log(msg): void {
console.log(msg)
}


&
2. React TS 공부한 부분 (Interface, Generic, with emotion)
function sum(x: number, y: number): number {
return x + y;
}
sum(1, 2);
function total(numbers: number[]): number {
return numbers.reduce((acc, cur) => acc + cur, 0)
}
function log(msg): void {
console.log(msg)
}
&
2. React TS 공부한 부분 (Interface, Generic, with emotion)
2. React TS 공부한 부분 (Interface, Generic, with emotion)
interface User {
id: number,
name: string,
}
export interface CardProps {
title: string,
subtitle: string,
user?: User // optional
}
function Card({
title,
subtitle
}: CardProps): React.ReactElement {
return (
<div>
{user?.name} // optional chaining
</div>
);
}
2. React TS 공부한 부분 (
Hook, Interface, Generic, with emotion
)
function vs arrow
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
export default () => {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
2. React TS 공부한 부분 (
Hook, Interface, Generic, with emotion
)
FC vs interface fc 기본 children 있음
import React, {FC} from 'react';
interface LogoProps {
src: string;
alt: string;
}
const Logo:FC<LogoProps> = ({src, alt, children}) => {
return (
<div>
<img src={src} alt={alt}/>
{children}
</div>
);
};
export default Logo;
2. React TS 공부한 부분 (
Hook, Interface, Generic, with emotion
)
interface children까지 작성
import React, {FC, ReactElement } from 'react';
interface LogoProps {
src: string;
alt: string;
children?: ReactElement;
}
const Logo = ({src, alt, children}: LogoProps) => {
return (
<div>
<img src={src} alt={alt}/>
{children}
</div>
);
};
export default Logo;
2. React TS 공부한 부분 (
Hook, Interface, Generic, with emotion
)
function merge(a: any, b: any): any {
return {
...a,
...b
};
}
const merged = merge({ foo: 1 }, { bar: 1 });
function merge<A, B>(a: A, b: B): A & B {
return {
...a,
...b
};
}
const merged = merge({ foo: 1 }, { bar: 1 });
2. React TS 공부한 부분 (
Hook, Interface, Generic, with emotion
)
interface User {
name: string;
age: number;
}
interface Items<T> {
list: T[];
}
const items: Items<User> = {
list: [{name: 'dali', age: 3}]
};
class Queue<T> {
list: T[] = [];
get length() {
return this.list.length;
}
enqueue(item: T) {
this.list.push(item);
}
dequeue() {
return this.list.shift();
}
}
CSS in JS

CSS in JS
import React, { ReactNode } from 'react';
import styled from '@emotion/styled';
const StyledWrapper = styled.div`
width: 1170px;
margin: 0 auto;
display: flex;
align-items: center;
`;
//TODO Css props으로 받아서 처리할 수 있도록 작업
export interface WrapperProps {
children?: ReactNode;
className?: string;
}
export const wrapperStyle = {};
function Wrapper({ children, className }: WrapperProps) {
return <StyledWrapper className={className}>{children}</StyledWrapper>;
}
export default Wrapper;
CSS in JS
// TODO Wrapper에서 css props 받아서 처리하도록 수정
const SiteNavigationWrapper = styled(Wrapper)`
justify-content: space-between;
height: 40px;
`;
<Wrapper
css`justify-content: space-between; height: 40px;`
>
import { jsx } from '@emotion/core'
render(
<div
css={{
backgroundColor: 'hotpink',
'&:hover': {
color: 'lightgreen'
}
}}
>
This has a hotpink background.
</div>
)

Hooks
import React, { useState } from 'react';
function Example() {
// "count"라는 새로운 상태 값을 정의합니다.
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
Hooks
import React, { useState } from 'react';
function Example() {
// "count"라는 새로운 상태 값을 정의합니다.
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
Hooks
UseEffect
componentDidMount 나 componentDidUpdate, componentWillUnmount
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
useEffect(() => {
document.title = `You clicked ${count} times`;
});
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
Hooks
UseEffect
REF
2020 Prelog +
- 사내 기술 블로그 글 2편 이상 쓰기
- DB 부터 Node Ts로 간단한 TODO or 게시판 Service 정도 구축해보기
- Git, Docker 책 1권 이상 씩 읽고 공부하기
- 2주일에 블로그 글 1편 씩 쓰기
- 개인 프로젝트 서비스 분기 별로 하나씩 내보기
- 운동습관 ->지금 거의 체지방률 20%... -> 13%
- 새로운 취미 활동 하기
- 영어공부 시작하기 -> 일주일에 한 번 meetup 알아보기
- 서울 살이 -> 연말에는 집 알아보기
끝
React + TS vol.1
By chany
React + TS vol.1
...
- 337