简体   繁体   English

在函数中反应 setState 或在 useCallback 中反应 setState

[英]React setState in function or setState in useCallback

This looks simple but I am trying to find the best way of handling the state change, I know useCallback needed for large application but created the simple example for better understanding and deep analysis.这看起来很简单,但我试图找到处理状态更改的最佳方法,我知道大型应用程序需要useCallback ,但创建了简单的示例以更好地理解和深入分析。

So I want to understand which one is better approach with useCallback or without useCallback for less re-render and create function only once.所以我想了解哪一个更好的办法useCallback或不useCallback更少的重新渲染,打造功能只有一次。

In this code we are setting setState in onCheckChange , without useCallback .在这段代码中,我们在onCheckChange中设置setState ,没有useCallback


const App = () => {
  const [checked, setChecked] = useState(false)

  // Without UseCallback
  const onCheckChange = () => {
    setChecked(!checked);
  };
  return (
    <div className="App">
      <input type="checkbox" onChange={onCheckChange} checked={checked} />
    </div>
  );
}

In this code state will be updated through useCallback to avoid re-creation of onCheckChange在此代码状态将通过useCallback更新以避免重新创建onCheckChange

const App = () => {
  const [checked, setChecked] = useState(false)

  // Callback to update Sate
  const onCheckChange = useCallback(() => {
    setChecked(checked => !checked);
  }, [setChecked]);

  return (
    <div className="App">
      <input type="checkbox" onChange={onCheckChange} checked={checked} />
    </div>
  );
}

One could simply write since the identity of the function setChecked never changes.可以简单地写,因为函数setChecked的身份永远不会改变。

const onCheckChange = useCallback(() => {
  setChecked(checked => !checked);
}, []);

Note笔记

React guarantees that setChecked function identity is stable and won't change on re-renders. React 保证 setChecked 函数标识是稳定的,并且不会在重新渲染时发生变化。 This is why it's safe to omit from the useEffect or useCallback dependency list.这就是为什么从 useEffect 或 useCallback 依赖项列表中省略是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM