Skip to content

Instantly share code, notes, and snippets.

@marcolink
Last active January 15, 2019 15:22
Show Gist options
  • Save marcolink/6088140aa4334c5e52a07a5f688afe1b to your computer and use it in GitHub Desktop.
Save marcolink/6088140aa4334c5e52a07a5f688afe1b to your computer and use it in GitHub Desktop.
destructing custom react hooks

Destruct custom react hooks (with typescript)

Bad

const [myValue] = useCustomHook();
//or
const [myValue, setMyValue] = useCustomHook();
//or
const [myValue, setMyValue, isMyValueValid] = useCustomHook();

Cons: in TS (depending on your liniting settings) you can't use isMyValueValid without actually using setMyValue.

Good

const {myValue, setMyValue, isMyValueValid} = useCustomHook();
//or
const {myValue} = useCustomHook();
//or
const {isMyValueValid} = useCustomHook();
//or
const {myValue, isMyValueValid} = useCustomHook();
//or
const {myValue, setMyValue} = useCustomHook();
//or
const {setMyValue} = useCustomHook();
//and so on ...

Pros: You can destruct any subset of fields you want to expose, regardless the order. You have to use defined field names (better consistency)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment