Header logo.
small hallucinations
homeyearstagsaboutrss

A simple demo of how useCallback works

This is how useCallback works.

In the callback defined on line 🙄, the function body increases the count by 1. We set the dependency list to be shallChange. This way, the count will not increase unless shallChange gets a different value.

If you click Count+ multiple times, the count will only increase once. It will increase again after you click Shall Change? butotn.

 1import { useCallback, useState } from 'react';
 2
 3function App() {
 4  const [count, setCount] = useState(0);
 5  const [shallChange, setShallChange] = useState(0);
 6
 7  const setCountCallback = useCallback( // 🙄
 8    ()=> {
 9      setCount(count+1)
10    }, [shallChange]
11  )
12  
13  const onPlusBtnClick = () => {
14    setCountCallback();
15  }
16
17  const onShallChangeClick = () => {
18    setShallChange(shallChange+1)
19  }
20  
21  return (
22    <div>
23        Count: {count}<br />
24        shallChange: {shallChange}<br />
25        <button onClick={onPlusBtnClick}>Count+</button><br />
26        <button onClick={onShallChangeClick}>Shall change?</button>
27    </div>
28  );
29}
30
31export default App;