Feature Request: New hook `useToggleState`

This issue has been tracked since 2022-09-19.

Summary
Many times we have ended up writing a toggle function like this

const [ subtitles, setSubtitiles ] = useState(false);
const toggleSubtitles = () => setSubtitles((prevState) => !prevState);

The toggleSubtitles function exist purely to toggle the state. This can be taken care of by the new hook useToggleState.

API
useToggleState will be used to create state variables like normal, however instead of returning a getter for setting a state, we get a toggle state function

const [ subtitles, toggleSubtitles ] = useToggleState(false); 

If we also want to get the original setter for this state, we can de-structure a third argument.

const [ subtitles, toggleSubtitles, setSubtitles ] = useToggleState(false); 

or toggleSubtitles can accept a boolean value as well, which will set the state to the value passed

toggleSubtitles() // toggles state between true and false
toggleSubtitles(true) // will set the state to be true
toggleSubtitles(false) // will set the state to be false

Alternative

  • We can also modify useState to return a toggle function as a third de-structure.
  • We can write our own custom hook for this feature but it would mean it has to be replicated on each and every repo.
EliHood wrote this answer on 2022-09-21

Idkk.... about this feature, i feel like react shouldn't support this. It would be an OK feature to have for a third party package though. That's just me though.

wenzi0github wrote this answer on 2022-09-21

Generally, js library only provides basic capabilities. useToggleState can be supported by useState.

/**
 * toggle true or false to another
 * @param {boolean} defaultVal
 * @returns
 */
const useToggleState = (defaultVal = true): [boolean, (val?: boolean) => void] => {
  const [subtitles, setSubtitiles] = useState(defaultVal);

  const toggleSubtitles = (bool?: boolean) => {
    setSubtitiles((prevState) => bool ?? !prevState);
  };

  return [subtitles, toggleSubtitles];
};
const [subtitles, toggleSubtitles] = useToggleState();
kkyusufk wrote this answer on 2022-09-21

Agreed with all of you.
I just wanted to get a second opinion from folks and I think after consideration, we actually do not need this.
Thanks all for sharing your thoughts, will close this issue.

More Details About Repo
Owner Name facebook
Repo Name react
Full Name facebook/react
Language JavaScript
Created Date 2013-05-24
Updated Date 2022-10-05
Star Count 195628
Watcher Count 6648
Fork Count 40518
Issue Count 1111

YOU MAY BE INTERESTED

Issue Title Created Date Updated Date