首页 > 解决方案 > useState React 实现

问题描述

我看到了两种不同的 useState 实现,我想知道它们的区别。

  const [count, setCount] = useState(0);
  ...
  // First: using var from useState
  setCount(count + 1);
  // Second: using prevState in a function
  setCount(count => count + 1);

标签: reactjsreact-nativeuse-state

解决方案


// Will not be re fired until UI is re rendered e.g you have a cart and you wanna increment the number of products in the cart. That way you can ensure that in case the user hit the increment button twice by accident the number wont increment twice before it‘s re rendered
 setCount(count + 1); 

// Will update count twice unless a rerendered were completed
setCount(count => count + 1);

推荐阅读