Created
November 4, 2021 00:17
useEncapsulation
This file contains hidden or 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
// Cleaner way to manage state and its handlers | |
import React, { useState, useMemo } from 'react'; | |
const Home = (props) => { | |
const [count, { inc, dec }] = useCounter(); | |
return ( | |
<main id="home-component" className="component-container"> | |
<h5>Count {count}</h5> | |
<a onClick={() => inc(count)}>Inc.</a> | |
<a onClick={() => dec(count)}>Dec.</a> | |
</main> | |
); | |
}; | |
const useCounter = () => { | |
const [state, update] = useState(0); | |
const handlers = useMemo(() => ({ | |
inc: (n) => update(n + 1), | |
dec: (n) => update(n - 1), | |
})); | |
return [state, handlers]; | |
}; | |
export default Home; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment