Skip to content

Instantly share code, notes, and snippets.

@basarat
Last active February 5, 2020 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save basarat/2b0371af4d431c140a4155c312db2ab5 to your computer and use it in GitHub Desktop.
Save basarat/2b0371af4d431c140a4155c312db2ab5 to your computer and use it in GitHub Desktop.
React useReuse pattern 🌹
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>
);
}
// 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>
);
}
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