Last active
October 1, 2021 01:19
-
-
Save lightsound/8d07115c8cec4f0277bf20fe45730073 to your computer and use it in GitHub Desktop.
useSharedState
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
test.tsx
は講座で使用したコードuseSharedState.ts
はTypeScriptで使うために抜き出したものです