본문 바로가기
카테고리 없음

react 언마운트 시점에 요청 한번만 보내기

by juniKang 2023. 12. 7.
import { useState, useEffect } from 'react';

type Props = {
  handleValueChange: (val: string) => void
  value: string
};

const Case700 = ({ handleValueChange, value }: Props) => {
  const [val, setVal] = useState(value);

  const unmount = () => {
    console.log(val);
    handleValueChange(val ?? '');
  };

  useEffect(() => unmount, []);
  return (
    <input
      type="text"
      placeholder="이유를 입력해주세요.."
      value={val}
      onChange={(e) => {
        console.log(val);
        setVal(e.target.value);
      }}
    />
  );
};

export default Case700;

이렇게하면 unmount함수가 만들어 질 때, 클로져에 의해 val가 초기값으로 고정된다.

import { useState, useEffect, useRef } from 'react';

type Props = {
  handleValueChange: (val: string) => void
  value: string
};

const Case700 = ({ handleValueChange, value }: Props) => {
  const [val, setVal] = useState(value);
  const valRef = useRef(val);

  const unmount = () => {
    handleValueChange(valRef.current);
  };

  useEffect(() => unmount, []);
  return (
    <input
      type="text"
      placeholder="이유를 입력해주세요.."
      value={val}
      onChange={(e) => {
        valRef.current = e.target.value;
        setVal(e.target.value);
      }}
    />
  );
};

export default Case700;

그래서 이렇게 해야 됌

댓글