alibaba / hooks

A high-quality & reliable React Hooks library. https://ahooks.pages.dev/
https://ahooks.js.org/
MIT License
13.95k stars 2.7k forks source link

feat: add useValueMutation #2622

Open FanetheDivine opened 2 months ago

FanetheDivine commented 2 months ago

[中文版模板 / Chinese template]

🤔 This is a ...

🔗 Related issue link

💡 Background and solution

修复上次pr中此hook存在的bug
在开发中经常遇到这样的需求:受控组件要防抖地进行更新.这个hook可以解决这个问题.

const InputWithMutation: FC<{ value: string; onChange: (newVal: string) => void }> = (props) => {
  const [value, onChange] = useValueMutation(props.value, props.onChange);
  return <input value={value} onChange={(e) => onChange(e.target.value)} />;
};

InputWithMutation可以在受控的同时接受一个经过防抖处理的onChange作为参数

const Demo1: FC = () => {
  const [text, setText] = useState('');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'start' }}>
      <button onClick={() => setText(Math.random().toString(36).slice(2))}>mutate</button>
      {text}
      <InputWithMutation value={text} onChange={debounce(setText, 1000)} />
    </div>
  );
};

现在可以在输入框内自由输入 同时在text突变的时候控制输入框内的值
相比useControllableValue,这个钩子允许组件在受控/非受控间自由切换而不需要对value做特殊处理,也可以用于防抖、transition等异步更新情形 参考https://codesandbox.io/p/devbox/test-usevaluemutation-nfcnk3

📝 Changelog

Language Changelog
🇺🇸 English add hook useValueMutation
🇨🇳 Chinese 增加钩子useValueMutation

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️