Skip to content

Instantly share code, notes, and snippets.

@alfonsodev
Last active July 11, 2017 10:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfonsodev/81b71e9dba2632b3ab6a1f7f35bfd915 to your computer and use it in GitHub Desktop.
Save alfonsodev/81b71e9dba2632b3ab6a1f7f35bfd915 to your computer and use it in GitHub Desktop.
Refactoring React Views, checkpoints

Refactoring view general checkpints

1. Insert // @flow

in the header of the file, in this way the flowtype binary will not ignore the file, and will statically analise it.

2. Add props types to you view.

Proptypes is deprecated in react-native, the way Facebook team is going forward is using flowtype. To specify the types of properties

type Props = {
  title: string,
  visited: boolean,
  onClick: () => void,
};

class Button extends React.Component {
  props: Props;

More info: https://flowtype.org/docs/react.html#_

3. Add types to function arguments:

  function greatestCommonDivisor(a: number, b: number): number {

4. Make sure all private methods start wiht underscore _

Rename methods that are used to handle events with 
the prefix _handle{event name}{Element Who Triggres it }
Examples : 
		_handleOnPressContinueButton 
		_handleOnFinishSmartLyrics

5. Binding:

Remove this._myFunction = this._myFunction.bind(this) from constructor if exting Remove onPress={this._myFunction.bind(this)} on press Instead declare methods that need binding as fat arrow function

	class Button extends React.Component {

		_hanldeOnPressContinueButton = () => {
    }

The onPress call nees to be like this

onPress={()=>{ this._hanldeOnPressContinueButton() }}

instead of

onPress={this._hanldeOnPressContinueButton().bind(this)}

Try the shorter onPress={()=>his._hanldeOnPressContinueButton()} if is correct, I think so.

6 Import Ract and Component from React

import React, { Component } from 'react';

Instead of importing those from 'react-native'

Also instead of

import React           from 'react-native'
const {
  Text,
  Image
} = React

You can import react-native components directly

import { Text, Image } from 'react-native'

7 Flowtype class properties

Declare the class properties with flow anotation

class MyClass {
  foo: string;
  constructor(foo: string) {
    this.foo = foo;
  }
}

8 Minimise state variables

Setting a state variable triggers a new render, therefoe only make sense to hold in the state object variables that are used in the render() method of the class. Otherwise just use private class properties, that doesn't trigrrer the react life cycle when changed,

9 General refactor principles

  • Untagle long methods that are making to many tings in smaller functions that do one thing.
  • Identify variable names that are ambigous or missleading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment