교육 (Today I Learned)/Hanaro

[Hanaro] 29일차 / React (Hooks- memo, useDeferredValue, useTransition), Component Styling, Routing

Bay Im 2024. 2. 28. 09:14

02 React Hooks

  • memo
    • memo란
      • component memoization
      • 컴포넌트가 props로 동일한 결과를 랜더링하면 memo를 호출하고 결과를 memoizaing하여 성능 향상 (마지막으로 랜더링된 결과를 재사용)
      • props 변화에만 영향을 주고 state, context가 변하면 재랜더링
    • 기본 형태
      • memo(Component, (pre, curr) ⇒ !!cache);
        • 두번째 함수가 true를 반환하면 cache
    • 예시
      • memo(Component, () ⇒ true)
        • 영원히 cache
      • memo(Component, ({prop: a}, {prop: b}) ⇒ a === b);
        • 이전 상태값과 현재 전달된 값이 같으면
  • useId
    • 고유한 ID를 생성해주는 hook
    • 변경될 수 있는 곳(key, selector 등)에서는 사용하지 말 것
    • LabelInput 컴포넌트를 여러 개 사용시 DOM의 id 중복 문제 해결
  • useDeferredValue
    • useDeferredValue(state)란
      • 상태 값 변화에 낮은 우선 순위를 지정하기 위한 hook
      • setState 완료하고 set
      • useMemo와 함께 많이 사용된다.
    • 기본형태
      • import { useDeferredValue } from ‘react’;
      • const [str, setStr] = useState(’’);
      • const deferredStr = useDeferredValue(str);
  • useTransition
    • useTransition(cb)란
      • 상태 변화의 우선순위를 지정하기 위한 hook
      • 모든 setState 완료하고 cb를 call
    • 기본형태
      • import { useTransition } from ‘react’;
      • const [str, setStr] = useState(’’);
      • const [list, setList] = useState<{ id: number; value: string }[]>([]);
      • const [isPending, startTransition] = useTransition();
  • browser storage
    • localStorage
      • localStorage란
        • 브라우저의 데이터 저장 공간 (Web Storage)
        • domain별 반 영구적으로 보관 가능 (만료기간 설정 불가, 직접 구현)
        • key & value pair (모두 string 타입) 모두 동기적 처리
      • method
        • getItem, setItem, removeItem, clear
      • 예시
        • const data = {id: 1, name: 'Hong'};
          localStorage.setItem('user', JSON.stringify(data));
          JSON.parse(localStorage.getItem('user'));
          localStorage.removeItem('user');
          localStorage.clear();  // 모두 삭제
    • sessionStorage
      • sessionStorage란
        • 브라우저의 Session별 데이터 저장 공간 (Web Session Storage)
        • domain별 일시적으로 보관 가능 (window.sessionStorage)
        • 브라우저 닫으면 날아감
        • 나머지는 localStorage와 동일 (logout시 clear)

 

03 React - Component Styling

  • React Component Styling
    • 일반 CSS file (React defaults)
      • CSS 파일 import 하여 사용
        • import ‘./App.css’;
        • className=’xxx’
      • import styles from ‘./App.css’
        • className={styles.App} 또는
        • className={${styles.active} ${styles.bold}}
      • CSS 모듈
        • import styles from ‘./App.module.css’;
        • .xxx
        • App_xxx__<uniqId> (파일명_클래스_해시값)
        • 클래스명 중복 방지 및 해당 컴포넌트에서만 사용된다.
    • styled-components 모듈
      • const Ul = styled.<tag>list-style: none;...;
        • <ul>...</ul>
        • <Ul>...</Ul>
      • const StyledCompo = styled(Compo)css 구문 ...;
        • <StyledCompo … />
        • Compo = ({className})
        • <div className={className} …
    • classnames 모듈
      • import classNames from 'classnames';
        • <div classNames={classNames('foo', {'bar': isActive}, isActive ? 'xxx' : '')}>
      • import classNames from 'classnames/bind';
        • const cx = classNames.bind(styles);
        • <div className={cx('cls', 'bbb', {ccc: true})}>
        • <div className={({ isActive }) => cx({ active: isActive })}>
    • jss 모듈
    • emotion 모듈

 

04 React - Routing

  • react-router-dom 설치
    • npm i react-router-dom
    • npm i -D @types/react-router-dom
  • react-router-dom
    • 라우터 타입(최상위)
      • BrowserRouter
      • HashRouter
      • MemoryRouter
    • 페이지 라우팅
      • Routes > Route
      • Routes는 여러 개 둘 수 있다.
  • React Router (Navigate & useNavigate)
    • import
      • import { Navigate, useNavigate } from 'react-router-dom';
    • 페이지 강제 이동 (forward/redirect)
      • <Navigate to='<path>' state={} />
      • <Route path='/old-path' element={<Navigate to='/new-path'/>} />
  • React Router (Nav)
    • Link (페이지 링크)
      • <Link to='/items' [replace | reloadDocument] />
    • NavLink
      • isActive callback 함수 제공 (children, className, style)
  • NavLink Styling
    • styled-component & emotion
      • active 처리
        • Route의 path와 NavLink의 to가 일치하면 active 클래스를 자동으로 넣어준다.
    • classnames
      • Modue CSS + classnames 로 처리
        • Module CSS로 클래스 중복 막고, isActive 처리는 classnames로 처리
    • clsx
      • active 처리
        • css 파일에서 active 클래스 설정
        • 가장 단단 (클래스 중복은 상위 클래스로 설정)