UseState implements’ callback ‘

The team recently moved from class components to functional components and ran into a problem with setting callback methods in useState.

React Hook, setState was officially removed from the callback method. Since setState is an asynchronous method, it cannot get the latest data directly after set, so we can get the updated value in the following two ways.

  1. UseEffect implementation
const [count, setCount] = useState(0);

const addCount = () => {
   setCount(count+1);
};

useEffect(() => {
   console.log(count);
   function(){
   ....
   }
}, [count])
Copy the code

UseEffect allows you to implement the ‘callback’ method by listening for count changes.

  1. Promise to realize
const [count, setCount] = useState(0); const addCount = () => { new Promise((resolve) => { setCount((num) => { resolve(num + 1); return num + 1; }); }).then(res => { console.log(res); . }); };Copy the code

The setState callback is officially removed and useEffect is preferred.