0

Background

I'm making timer using React-Hook and Functional Component. The code below is working well.

type TProps = {
  startTime: string;
  lapTime: number;
};

export default function RemainTime({ lapTime }: TProps) {
  const [lt, setLapTime] = useState<number>(lapTime);
  useEffect(() => {
    console.log('lapTime is changed');
    const timer = setInterval(() => {
      console.log('setInterval is called');
      setLapTime((prev) => prev - 1);
    }, 1000);
    return () => {
      console.log('component unmounted');
      clearInterval(timer);
    };
  }, [lapTime]);
  return <div>Remain Time : {lt}</div>;
}

The lt changes every second.

Problem

Even though I re-render the RemainTime component with new props({ lapTime: 300 }), the lt has a previous value.

What I want

I want the RemainTime component to render new time when the lapTime is changed.

Byeongin Yoon
  • 3,233
  • 6
  • 26
  • 44

1 Answers1

0

I found answer.

type TProps = {
  startTime: string;
  lapTime: number;
};

export default function RemainTime({ lapTime: initialLapTime }: TProps) {
  const [lapTime, setLapTime] = useState<number>(initialLapTime);
  useEffect(() => {
    setLapTime(initialLapTime);
    const timer = setInterval(() => {
      setLapTime((prev) => prev - 1);
    }, 1000);
    return () => {
      console.log('component unmounted');
      clearInterval(timer);
    };
  }, [initialLapTime]);
  return <div>Remain Time : {lapTime}</div>;
}
Byeongin Yoon
  • 3,233
  • 6
  • 26
  • 44
  • 1
    Every useEffect should have a single responsibility, you should move this logic to another useEffect. Check it in React docs or/and notes from here: https://stackoverflow.com/questions/59841800/react-useeffect-in-depth-use-of-useeffect/59841947#59841947 – Dennis Vash Feb 03 '22 at 14:12