Last active
February 5, 2020 22:46
-
-
Save basarat/2b0371af4d431c140a4155c312db2ab5 to your computer and use it in GitHub Desktop.
React useReuse pattern 🌹
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
export function App() { | |
const counterOne = useCounter(); | |
const counterTwo = useCounter(); | |
return ( | |
<div> | |
<Counter use={counterOne}/> | |
<Counter use={counterTwo}/> | |
{/* Able to use the counters for any additional logic */} | |
<div>Total Count: {counterOne.count + counterTwo.count}</div> | |
</div> | |
); | |
} |
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
// Some hooks the component needs | |
export function useCounter() { | |
const [count, setCount] = useState(0); | |
return {count, setCount}; | |
} | |
// Infer the props | |
export type CounterProps = { | |
use: ReturnType<typeof useCounter> | |
} | |
// The rendering of the component | |
export function Counter({ use }: CounterProps) { | |
return ( | |
<div> | |
<p>You clicked {use.count} times</p> | |
<button onClick={() => use.setCount(count + 1)}> | |
Click me | |
</button> | |
</div> | |
); | |
} |
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
function Counter() { | |
// Some hooks the component needs | |
const [count, setCount] = useState(0); | |
// The rendering of the component | |
return ( | |
<div> | |
<p>You clicked {count} times</p> | |
<button onClick={() => setCount(count + 1)}> | |
Click me | |
</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment