본문 바로가기

Programming/React

SWR로 로컬 상태 컨트롤 - Counter

반응형

 

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>
  );
}

 

반응형