Header logo.
Small Hallucinations
HomeArchiveTagsAboutFeed

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.

import { useCallback, useState } from 'react';

function App() {
  const [count, setCount] = useState(0);
  const [shallChange, setShallChange] = useState(0);

  const setCountCallback = useCallback( // 🙄
    ()=> {
      setCount(count+1)
    }, [shallChange]
  )

  const onPlusBtnClick = () => {
    setCountCallback();
  }

  const onShallChangeClick = () => {
    setShallChange(shallChange+1)
  }

  return (
    <div>
        Count: {count}<br />
        shallChange: {shallChange}<br />
        <button onClick={onPlusBtnClick}>Count+</button><br />
        <button onClick={onShallChangeClick}>Shall change?</button>
    </div>
  );
}

export default App;