30秒学会 React 片段 · 2023年2月16日

30秒学会 React 片段 – React useToggler hook

Provides a boolean state variable that can be toggled between its two states.

  • Use the useState() hook to create the value state variable and its setter.
  • Create a function that toggles the value of the value state variable and memoize it, using the useCallback() hook.
  • Return the value state variable and the memoized toggler function.

代码实现

const useToggler = initialState => {
  const [value, setValue] = React.useState(initialState);

  const toggleValue = React.useCallback(() => setValue(prev => !prev), []);

  return [value, toggleValue];
};

使用样例

const Switch = () => {
  const [val, toggleVal] = useToggler(false);
  return <button onClick={toggleVal}>{val ? 'ON' : 'OFF'}</button>;
};
ReactDOM.createRoot(document.getElementById('root')).render(
  <Switch />
);

翻译自:https://www.30secondsofcode.org/react/s/use-toggler