React Basic Hooks Example - More than on useState()
by Paco86
HTML
<div id="root"></div>
CSS
body {
height: 100vh;
font-family: 'Open Sans', sans-serif;
font-weight: bold;
font-size: 24px;
display: flex;
justify-content: center;
align-items: center;
}
React
const useState = React.useState;
const useEffect = React.useEffect;
function debounce(fn, ms) {
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn(...args)
timer = null;
}, ms);
}
}
function useDebounce(fn, time) {
return debounce(fn, time);
}
function Example() {
const [counter1, setCounter1] = useState(0);
const [counter2, setCounter2] = useState(0);
const handleClick = useDebounce(function() {
console.log('usedebounce')
setCounter1(counter1 + 1)
}, 500)
useEffect(function() {
const t = setInterval(() => {
setCounter2(x => x + 1)
}, 500);
return clearInterval.bind(undefined, t)
}, [])
return (
<div style={{ padding: 30 }}>
<button onClick={handleClick}>
click
</button>
<div>{counter1}</div>
<div>{counter2}</div>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'))