Skip to content

Instantly share code, notes, and snippets.

@lightsound
Last active October 1, 2021 01:19
Show Gist options
  • Save lightsound/8d07115c8cec4f0277bf20fe45730073 to your computer and use it in GitHub Desktop.
Save lightsound/8d07115c8cec4f0277bf20fe45730073 to your computer and use it in GitHub Desktop.
useSharedState
import useSWR from "swr";
const useSharedState = (key: string, fallbackData: any) => {
const { data, mutate } = useSWR(key, { fallbackData });
return [data, mutate];
};
const useCounter = () => {
const [count, setCount] = useSharedState("counter", 0);
const handleIncrement = () => {
setCount(count + 1);
};
return { count, handleIncrement };
};
const useText = () => {
const [text, setText] = useSharedState("text", "");
const handleChange = (e) => {
setText(e.target.value);
};
return { text, handleChange };
};
const Test = () => {
return (
<>
<ChildrenA />
<ChildrenB />
</>
);
};
const ChildrenA = () => {
const { text } = useText();
return <div>{text}</div>;
// const { count } = useCounter();
// return <div className="bg-red-800">{count}</div>;
};
const ChildrenB = () => {
const { text, handleChange } = useText();
return (
<div>
<div>{text}</div>
<input type="text" value={text} onChange={handleChange} />
</div>
);
// const { count, handleIncrement } = useCounter();
// return (
// <div className="bg-blue-800">
// <div>{count}</div>
// <button onClick={handleIncrement}>Increment</button>
// </div>
// );
};
export default Test;
import useSWR from "swr";
import type { KeyedMutator } from "swr/dist/types";
export const useSharedState = <T extends any>(key: string, fallbackData?: T) => {
const { data, mutate } = useSWR(key, { fallbackData });
return [data, mutate] as [typeof fallbackData, KeyedMutator<typeof fallbackData>];
};
@lightsound
Copy link
Author

lightsound commented Sep 13, 2021

test.tsxは講座で使用したコード
useSharedState.tsはTypeScriptで使うために抜き出したものです

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment