Feature Request: New hook `useToggleState`

This issue has been created 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-09-26
Star Count 195293
Watcher Count 6655
Fork Count 40426
Issue Count 1113

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
URGENT: AFTER CHANGING THE ACCOUNT SUBSCRIPTION WE RECEIVE THE PAYMENTS IN BOTH ACCOUNTS (this is the 2nd month) 0 2022-07-29 2022-08-15
PC에서 기존글 수정 시 새 글로 등록되는 이슈 3 2021-09-12 2022-07-12
There seems to be an OOM issue. 4 2022-02-10 2022-08-25
Molecule/Autosuggest aria-expanded true when dropdown closed 0 2022-03-17 2022-07-15
Can I use Down to convert an NSAttributedString to a markdown String? 1 2021-06-21 2022-09-22
Import error: No module named ipaddress 4 2015-02-09 2022-07-22
Senren * Banka window goes black when workspace in GNOME is changed or when you run the game in full-screen 3 2021-11-17 2022-09-26
How do I use sacreBleu with a Syriac language 2 2022-02-20 2022-09-16
[Feature Request] Allow diferent URL schemes 5 2022-02-07 2022-09-19
Support different relays for different domains 0 2021-12-11 2022-09-12
[Enhancement] Rely on external helm charts for database deployment 4 2022-01-21 2022-09-12
Persistence size for each component 0 2022-05-19 2022-09-12
[BUG] Critical: your DNS resolver isn't doing DNSSEC validation 12 2022-02-10 2022-09-12
Manually inputting a leading zero causes the month/day to have 3 digits 4 2020-02-17 2022-09-05
Convert population section on manage accessions page to a nested datatable 0 2022-02-08 2022-09-26
Latex in a node title 1 2021-10-07 2022-08-30
Classpath lookup failure error with Calva on MS-Windows 1 2022-07-21 2022-09-02
Task :react-native-inappbrowser-reborn:compileDebugJavaWithJavac FAILED in v3.6.1 2 2021-06-29 2022-09-14
When Geofence is present removing a gridset makes the layer non accesible anymore 12 2021-02-05 2022-09-02
GeoServer Transaction event management should be made more robust wrt Exceptions 0 2021-02-15 2021-12-26
bag report 1 2021-10-07 2021-10-31
Move DB object freeze call after the app declaration 8 2022-05-08 2022-09-16
ocsp/responder: implement sampling of errors 0 2022-09-01 2022-09-26
toContainHTML does not handle self-closing tags 2 2021-03-10 2022-09-16
Blackbird fails to deserialize varargs array 12 2021-06-24 2022-09-19
Please update jaxb dependency to 3.0.0 5 2021-03-10 2022-09-19
wallet database_path and can I delete blockchain_wallet_v1_mainnet_1_xxxxx.sqlite after db upgrade to v2 4 2022-04-23 2022-09-20
ARO to support confidential computing nodes to meet regulatory requirements 0 2021-11-11 2022-09-26
Okex sandbox problem with watch_orders. newUpdates : True sometimes does not work 34 2022-03-19 2022-09-12
Ver 4.4.0 Todo 3 2021-12-07 2022-01-15
希望支持视频倍速快捷键 0 2021-07-19 2022-01-15
[BUG] Possible Typo in chapter 16, Positional Embeddings 6 2022-03-10 2022-09-25
Missing Variables in Publisher in page 5805 "Item Charge Assignment (Purch)" 1 2022-02-16 2022-09-16
suggestion 1 2019-10-22 2022-01-05
gcloud CLI typo? 11 2021-08-03 2021-12-30
[ARM AppConfiguration] Hardcoded subscription id breaks Smoke Tests 1 2022-04-06 2022-09-26
`oneOf` containing only a single enum (or ref to one) does not display as drop-down 2 2022-03-15 2022-09-26
Swagger UI Could not resolve reference: Could not resolve pointer: After upgrading to SwashBuckle 6.3.0 with latest Swagger UI 3 2022-03-15 2022-09-21
Error on JS IR backend: generic base class with more than one type parameter 0 2021-09-22 2022-09-23
Make Profiles more pluggable, move Profile implementation to OCIProfile 2 2017-06-09 2022-09-20
FailedCreatePodContainer 1 2021-11-13 2022-08-30
This method cannot be used with the terraform s3 backend 3 2018-04-13 2022-09-25
👋 Open call for discussion to suggest focus areas for Security WG 8 2021-10-11 2022-09-08
Once symbolic 9.1 is released, update Cargo.toml 0 2022-08-02 2022-09-16
Running `npx @bookshop/init` inside an existing module-type npm package fails 0 2022-06-09 2022-09-18
Site suggestion 1 2019-05-21 2022-01-23
Apache HBase channel adapters & gateways support 0 2022-04-09 2022-09-21
Allow customization of single logout in auto-configured SAML relying party registration 8 2022-03-09 2022-09-24
[wasm] Stack overflow in `JIT/Directed/tailcall/tailcall/tailcall.sh` on Linux 1 2022-05-18 2022-05-13
date & time range filter ? 35 2022-02-01 2022-09-26