2104 TIL

Apr 1st 2021 by jyoon

210430

[CSS]cssText

dom.style.cssText = color: yellow; background: blue;;

[CSS]transform & transition 용어의 의미

210429

[JS]setState & callback function & async

  • use callback in setState 1st parameter
  • setState는 비동기로 동작하기 때문에 바로 수행되지 않는다.
  • 동기로 바로 수행해주기 위해서는 setState 첫번째 함수에 callback fn을 사용한다.

[React-Hooks]React.useCallback

[React-Hooks]React.useRef

  • useRef

    • eg

      const refContainer = useRef(initialValue);
    • point1. returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).
    • point2. The returned object will persist for the full lifetime of the component.
    • point3. dom객체를 직접 연결하는 방법

      • code

        function TextInputWithFocusButton() {
        const inputEl = useRef(null);
        const onButtonClick = () => {
          // `current` points to the mounted text input element
          inputEl.current.focus();
        };
        return (
          <>
            <input ref={inputEl} type="text" />
            <button onClick={onButtonClick}>Focus the input</button>
          </>
        );
        }
      • You might be familiar with refs primarily as a way to access the DOM. If you pass a ref object to React with
        , React will set its .current property to the corresponding DOM node whenever that node changes.
      • point4. .current가 변경될때 re-render되지 않는다.
      • point5. React가 ref를 DOM node에 붙고 떨어질때 코드를 실행시키고 싶다면 => callback ref를 사용해라

[React-Hooks]React.useRef (& instance variables)

  • Is there something like instance variables?

    • point1. Hook isn’t just for DOM refs.
    • point2. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.
    • point3. eg -> setTimeout, setInterval 등의 return value를 유지 했다가 clear해줄때 사용

[React-Hooks]useCallback(meassure a dom node)

  • How can I measure a DOM node?
  • point1. useRef를 사용하지 않은 이유는 curren ref value가 변경 되도 notify 되지 않는다.
  • point2. useCallback을 사용하면 자식 컴포넌트가 화면에 보여져 뒤늣게 노드가 계산되어도 (예를 들어 클릭에 대한 반응), 부모 컴포넌트에 notify되고 측정된 정보 알림을 받고 업데이트 할 수 있다.
  • point3. useCallback의 종속성 []을 기입 했을때 re-render를 하지 않는다.
  • point4. 아래 예에서 h1 은 마운트, 언마운트 때만 useCallback이 호출 된다.(h1 컴포넌트는 모든 rerender에 유지되기 때문에)
  • point5. 컴포넌트가 resize 될때 알림을 받기 위해서는 ResizeObserver를 사용하거나 third-party Hook 을 사용해야 한다.
  • point6. useRef -> useCallback -> ResizeObserver || third-party hok
  • code

    function MeasureExample() {
    const [height, setHeight] = useState(0);
    
    const measuredRef = useCallback(node => {
      if (node !== null) {
        setHeight(node.getBoundingClientRect().height);
      }
    }, []); //point3.
    
    return (
      <>
        <h1 ref={measuredRef}>Hello, world</h1>
        <h2>The above header is {Math.round(height)}px tall</h2>
      </>
    );
    }

    210428

    [JS]keyup이벤트에서 엔터가 입력되면 두번실행

    [JS]preventDefatult(), stopPropagation()

  • preventDefault

    • 태그의 고유 동작을 동작 시키지 않는다.
    • html 에서 a 태그나 submit 태그는 고유의 동작이 있다.
      페이지를 이동시킨다거나 form 안에 있는 input 등을 전송한다던가 그러한 동작이 있는데
      e.preventDefault 는 그 동작을 중단
    • submit은 페이지를 새로 고침하는데 그것을 방지
  • stopPropagation

    • event bubbling을 방지

      [CSS]getBoundingClientRect(return domRect 정보)

  • a DOMRect object providing information about the size of an element and its position relative to the viewport.
  • mdn - getBoundingClientRect
  • domRect

    • DOMRectReadOnly.x, .y, .width, .height, .top, .right, .bottom, .left
  • Viewport
  • Visual Viewport

210421

[DP]throttle, debounce

  • throttle

    • 연속적인 이벤트에 대해 꾸준히 변경사항을 반영하는 것이 필요 할때
    • 바에서 술 주문을 일정간격으로 받아 저세상 가는 것을 방지
    • eg) api call, mousemove/touchmove, prevent spam button click
  • debounce

    • 마지막 이벤트만을 감시(무한스크롤)
    • 식당에서 메뉴 주문이 다됐는지 확인으로 주방장 리소스 낭비 방지
    • 무한 스크롤시
    • eg) resize, scroll, save fn
  • Throttling and debounding in js

210420

[React-Hooks] useEffect 완벽가이드

  • useEffect 완벽 가이드
  • TLDR (Too Long; Didn’t Read - 요약)
  • 모든 랜더링은 고유의 Prop과 State가 있다
  • 모든 랜더링은 고유의 이벤트 핸들러를 가진다
  • 모든 랜더링은 고유의 이펙트를 가진다
  • 모든 랜더링은 고유의… 모든 것을 가지고 있다
  • 흐름을 거슬러 올라가기
  • 그러면 클린업(cleanup)은 뭐지?
  • 라이프사이클이 아니라 동기화
  • 리액트에게 이펙트를 비교하는 법을 가르치기
  • 리액트에게 의존성으로 거짓말하지 마라
  • 의존성으로 거짓말을 하면 생기는 일
  • 의존성을 솔직하게 적는 두 가지 방법
  • 이펙트가 자급자족 하도록 만들기
  • 함수형 업데이트와 구글 닥스(Google Docs)
  • 액션을 업데이트로부터 분리하기
  • 왜 useReducer가 Hooks의 치트 모드인가
  • 함수를 이펙트 안으로 옮기기
  • 하지만 저는 이 함수를 이펙트 안에 넣을 수 없어요
  • 함수도 데이터 흐름의 일부인가?
  • 경쟁 상태에 대해
  • 진입 장벽을 더 높이기
  • 마치며

[React-Hooks]]How to fetch data with React Hooks?