useMemo, useRef 를 이용한 input handling

이승민·2021년 11월 9일
0
  const handleInputFunction =
    useRef<(inputValue: string, name: string) => void>();
  handleInputFunction.current = (inputValue: string, name: string) => {
    if (name === "username") {
      setLoginInfo({ ...loginInfo, username: inputValue });
    } else {
      setLoginInfo({ ...loginInfo, password: inputValue });
    }
  };

  const onChangeInput = useMemo(
    () => (e: React.ChangeEvent<HTMLInputElement>) => {
      handleInputFunction.current?.(e.target.value, e.target.name);
    },
    []
  );

state에 input value를 저장하는 handleInputFunction 이라는 함수를 useRef를 이용해 생성한다. (함수가 실행되더라도 리렌더링 되지 않는다.)

그리고 input value가 변경되더라도 loginInfo 라는 state의 값을 기억하기 위해 onChangeInput 함수에 useMemo를 사용한다.

profile
프론트 앤드 개발자를 꿈꿉니다.

0개의 댓글