Skip to content

Code styleguide

Tim Stirrat edited this page May 2, 2020 · 9 revisions

General

No magic numbers or strings

Use constants for numbers

- arr.slice(0, 14);
+ arr.slice(0, MAX_EXPOSURE_DAYS);

Modules

Use named exports

Named exports have slightly better developer ergonomics in IDEs. The IDE can read the named export in files across the project even if you have not imported it before. Imports will always use consistent names. Names can be overridden with as, if needed.

Default exports are not easily discovered and lead to inconsistent names.

export const myVar = 1234;
export class MyClass {}

React components

Use functional components

export const MyComponent = () => {
  return <View />;
}

Use object spread assignment

This will clearly express inputs and outputs.

export const MyComponent = ({navigation, label}) => {
  return <View onPress={() => navigation.foo()}>{label}</View>;
}

JSDoc comment your input props

This will help the IDE infer types

/**
 * @param {{
 *   navigation: Navigation;
 *   label: string;
 * }} param0
 */
export const MyComponent = ({navigation, label}) => {
  return ...;
}

Use components, not methods, to group smaller abstractions of functionality

  <View>
-   {getSpecialViewStuff(label, color)}
+   <SpecialViewStuff label={label} color={color} />
  </View>

Use hooks

Hooks will keep your components concise.

export const MyComponent = () => {
  const [message, setMessage] = useState('hello');

  return <Text>{message}</Text>;
}

Keep complicated state or "business logic" out of views

Write custom hooks, with tests, to keep components small and reactive

export const MyComponent = () => {
  // example, not a real hook
  const [state, enable, disable] = useLocationTrackingState()

  return (
    <Text onPress={() => disable()}>
      {state === ENABLED ? 'Enabled': 'Disabled'}
    </Text>
  );
}
Clone this wiki locally