Sobes.tech
Junior — Senior

Sending the current meter reading to analytics on component unmount

livecode

Task condition

It is necessary to implement sending the current counter value to the analytics system at the moment when the component is removed from the DOM. It should ensure: ‑ saving the current counter value at unmount; ‑ no unnecessary send calls on each re-render or click.

function Component(props) {
  const [count, setCount] = useState(0);

  const onIncrement = () => {
    setCount(s => s + 1);
  };

  useEffect(() => {
    // send count on unmount
    return () => {
      // analyticsService.send(count)
    };
  }, []);

  if (count % 2 === 0) {
    return <MyButton handleClick={onIncrement} />;
  }

  return (
    <>
      <div>{count}</div>
      <MyButton handleClick={onIncrement} />
    </>
  );
}