React Hook API,我需要为 SetStateAction 设置依赖项吗?
React Hook API, should I need set deps for SetStateAction?
我对使用 React Hook 有疑问api
const Example: FC = (props) => {
const [str, setStr] = useState('example');
const onClickCb = useCallback(() => {
setStr(str + '_');
}, [str, setStr]); // should I need watch setStr?
return <button onClick={onClickCb}>{str}</button>;
};
不,您不需要添加 setStr
,因为它在组件的生命周期内不会更改。不过加上也没什么坏处,不会变。
Note
React guarantees that setState
function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect
or useCallback
dependency list.
但你绝对应该删除 str
。不应根据当前状态更新状态 react may batch multiple calls to setState
。这可能会导致在短时间内发生的更新丢失。而是使用 setState
:
的回调版本
const Example: FC = (props) => {
const [str, setStr] = useState('example');
const onClickCb = useCallback(() => setStr(current => `${current}_`)), []);
return <button onClick={onClickCb}>{str}</button>;
};
我对使用 React Hook 有疑问api
const Example: FC = (props) => {
const [str, setStr] = useState('example');
const onClickCb = useCallback(() => {
setStr(str + '_');
}, [str, setStr]); // should I need watch setStr?
return <button onClick={onClickCb}>{str}</button>;
};
不,您不需要添加 setStr
,因为它在组件的生命周期内不会更改。不过加上也没什么坏处,不会变。
Note
React guarantees that
setState
function identity is stable and won’t change on re-renders. This is why it’s safe to omit from theuseEffect
oruseCallback
dependency list.
但你绝对应该删除 str
。不应根据当前状态更新状态 react may batch multiple calls to setState
。这可能会导致在短时间内发生的更新丢失。而是使用 setState
:
const Example: FC = (props) => {
const [str, setStr] = useState('example');
const onClickCb = useCallback(() => setStr(current => `${current}_`)), []);
return <button onClick={onClickCb}>{str}</button>;
};