본문 바로가기
Programming/Javascript

SWR로 로컬 상태 컨트롤 - Counter

by Wilkyway 2021. 6. 26.

 

import useSWR from "swr";

function useCounter() {
  const { data, mutate } = useSWR("state", () => window.count);

  return {
    data: window.count || 0,
    mutate: (count) => {
      window.count = count;
      return mutate();
    },
  };
}

export default function Counter() {
  const { data, mutate } = useCounter();

  const handleInc = () => mutate(data + 1);
  const handleDec = () => mutate(data - 1);

  return (
    <div>
      <span>count: {data}</span>
      <button onClick={handleInc}>inc</button>
      <button onClick={handleDec}>dec</button>
    </div>
  );
}

 

댓글0