Skip to content

Code Style Guide

Todd Schiller edited this page Oct 13, 2021 · 16 revisions

Part of the Getting started guide.

This page is for capturing coding style guidelines that aren't automatically enforced by eslint

TypeScript

Use Map instead of objects/records where possible

Capitalize exported primitive constant names

This helps visually distinguish cross-module constants from local module variables

Bad:

const sidebarId = "sidebar";

Good:

const SIDEBAR_ID = "sidebar";

Include units in numeric constant names

Bad:

const MAX_WAIT = 1000;

Good:

const MAX_WAIT_MS = 1000;

Redux/Redux Toolkit

Provide a payload type when defining reducers in a slice

If you don't provide a type, Redux Toolkit assumes any

Bad:

removeExtension(
  state,
  { payload }
) {

Good:

removeExtension(
  state,
  { payload }: PayloadAction<{ extensionId: UUID }>
) {

Formik

useField

  • Pass a type parameter when using useField. The default is any do you don't get any type checking if you don't specify a type parameter
  • Do not use the helpers from useField. Consider using setFieldValue instead. https://github.com/formium/formik/issues/2268

Bad:

// `helpers` changes on every render :(
const [field, , helpers] = useField<boolean>();

Good:

const [field] = useField<boolean>();
const { setFieldValue } = useFormikContext();

useAsyncState

Do not pass an initialState unless you destructure and handle the error state.

Bad:

// The caller is oblivious to the error
const [value] = useAsyncState(async () => { throw Error() }, [], []);

Good:

const [value, isPending, error] = useAsyncState(async () => { throw Error() }, [], []);

// The caller is forced to deal with undefined
const [value] = useAsyncState(async () => { throw Error() }, []);