[TIL] 211206-07

먼지·2021년 12월 3일
0

TIL

목록 보기
3/57
post-thumbnail

모던 자바스크립트 Deep Dive 다시 읽기 1일차

04 변수

  • 메모리 공간에 저장된 값을 식별할 수 있는 고유한 이름을 변수명, 변수에 저장된 값을 변수 값. 변수에 값을 저장하는 것을 할당, 변수를 읽어 들이는 것을 참조라 한다. 식별자는 값이 아니라 메모리 주소를 기억하고 있음.
  • 변수 이름은 저장된 값의 의미를 명확히 파악할 수 있게
  • 호이스팅
    - 변수 선언문이 코드의 선두로 끌어 올려진 것처럼 동작하는 것
    - var, let, const, class 등의 키워드를 사용해 선언한 모든 식별자는 호이스팅 됨.
  • 식별자 네이밍 규칙
    - _, $를 제외한 특수문자x 예약어x 숫자로 시작x
  • 네이밍 컨벤션
    - camelCase let getName;
    - snake_case let get_name;
    - PascalCase const GetName
    - 자바스크립트는 일반적으로 카멜 케이스를 사용

05 표현식과 문

  • 값은 식이 평가되어 생성된 결과
10; // 10
10 + 30; // 40
  • 표현식은 값으로 평가될 수 있는 모든 문
const num = 50;
num; // 50
getName();
  • 문은 프로그램을 구성하는 기본 단위이자 최소 실행 단위
let x; // 변수 선언문
x = 4; // 할당문
function sayHello() { ... } // 함수 선언문
if (x) { ... } // 조건문
for (let i = 0; i < 4; i++) { ... } // 반복문

React

- props 내릴 때 원소가 많다면 깔끔하게 rest props 처리. 뭔가 헷갈려서 잘 사용하지 않았음.

const todoState = atom({
  key: 'todo',
  default: []
});

function Item({ id, text }) {
  return (
    ...
  );
} 

function TodoList() {
  const [todos, setTodos] = useRecoilState(todoState);
  ...
  return (
    <>
      ...
      <ul>
        {todos.map(todo => (
          <Item key={todo.id} {...todo} /> 
        ))}
      </ul>
    </>
  )
}

Typescript

- Installation

// 새 프로젝트
npx create-react-app my-app --template typescript
// 기존 프로젝트에 추가
npm install --save typescript @types/node @types/react @types/react-dom @types/jest

- interface

Typescript에게 object의 shape를 설명!

// App.tsx
import Test from './components/Test';
export default function App() {
  return (
    <>
      <Test text="hello" color="rosybrown" size="50" />
      <Test color="royalblue" size="100" />
    </>
  );
}

// Test.tsx
import styled from 'styled-components';
interface TestProps {
  text?: string; // string | undefined
  color: string;
  size: string;
}
interface ContainerProps {
  color: string;
  size: string;
}
const Container = styled.div<ContainerProps>`
  font-size: ${(props) => props.size}px;
  color: ${(props) => props.color};
`;
export default function Test({ text, color, size }: TestProps) {
  return (
    <Container color={color} size={size}>
      {text}
    </Container>
  );
}

- react event에 typescript 사용 시 event type을 알려주기 (https://ko.reactjs.org/docs/events.html)

구글링과 공식문서 열심히..

function App() {
  // (event) <- 'any' 무엇이든 될 수 있는 any type은 되도록 배제하기
  const onClick = (event: React.FormEvent<HTMLButtonElement>) => {...}
  const onInput = (event: React.FormEvent<HTMLSelectElement>) => {
    console.log(event.currentTarget.value);
    ...
  };
  
  return (
    <>
      <form>
        <button onClick={onClick}></button>
      </form>
      <select onInput={onInput}>
        ...
      </select>
    </>
  )
}

- enum은 일련의 숫자를 문자로 표현해줌. 타입이 정확하게 보장되지 않고 유니온 타입으로 대체 가능하며 따로 값을 정하지 않으면 자동으로 0부터 계산

export enum Days {
  'Monday', // 0
  'Tuesday' = 'Tuesday',
}

- Theme

// styled.d.ts - extend override declaration file
import 'styled-components';
declare module 'styled-components' {
  export interface DefaultTheme {
    bgColor: string;
  }
}

// theme.ts
import { DefaultTheme } from 'styled-components';
const theme: DefaultTheme = {
  bgColor: 'whitesmoke';
}

// index.tsx
import ReactDOM from 'react-dom';
import { ThemeProvider } from 'styled-components';
import App from './App';
import { theme } from './theme';
ReactDOM.render(
  <ThemeProvider theme={theme}>
    <App />
  </ThemeProvider>,
  document.getElementById('root')
);

// App.js
import styled from 'styled-components';
const Container = styled.div`
  background-color: ${(props) => props.theme.bgColor};
`;
export default function App() {
  return <Container></Container>;
}

Recoil

- useRecoilValue는 atom이나 selector의 값만 반환하고, useRecoilState는 값과 modifier 함수도 제공함

import { useRecoilState, useRecoilValue } from 'recoil';
import { firstState, firstSelector, secondState } from '../atoms';

function App() {
  const firstValue = useRecoilValue(firstState);
  const selectorValue = useRecoilValue(firstSelector);
  const [secondValue, setSecondValue] = useRecoilState(secondState);
  ...
}

- selector는 state를 받아서 변형해 반환해주는 함수로 key와 get function이 있음. 인자로 객체를 받고 이 객체에있는 또다른 get function으로 atom을 가져올 수 있으며 값을 얻어오려면 useRecoilValue를 사용함.

// atoms.js
export const firstState = atom({
  key: 'uniqKey',
  default: []
});
export const firstSelector = selector({
  key: 'uniqKey',
  get: ({ get }) => {
    const firsrtAtom = get(firstState);
    // return 값이 firstSelector의 value
    return ...;
  }
})

// App.js
import { useRecoilValue } from 'recoil';
import { firstSelector } from '../atoms';

funciton App() {
  const firstValue = useRecoilValue(firstSelector);
  ...
}

Immutability은 함수형 프로그래밍의 핵심 원리로 react의 state 변경 시 항상 새로운 state를 만들어 반환.

코드가 지저분해도 일단 작동하게 만들고 나중에 리팩토링!!

profile
꾸준히 자유롭게 즐겁게

0개의 댓글