Skip to content

Instantly share code, notes, and snippets.

@smhutch
Created August 10, 2020 18:54
Show Gist options
  • Save smhutch/17a108838ce0706f53ac41b237bb20f1 to your computer and use it in GitHub Desktop.
Save smhutch/17a108838ce0706f53ac41b237bb20f1 to your computer and use it in GitHub Desktop.
React tips

React

  1. Avoid state duplication. Instead, derive from props by transforming the state and ownProps in mapStateToProps. Example:
// This example assumes the same data structure as suggested below:
function mapStateToProps(reduxState, ownProps) {
  // ownProps = props passed to this component (some come from React router.)
	const { id } = ownProps.match.params
  const { lists } = state;

  // Get one list
  const list = lists[id]

  // Convert list data to only the data the component needs.
	return {
    id: list.id,
    title: list.title,
    tasks: tasks.filter(task => list.taskIds.includes());
}
  1. Consider abstracting list item to a component.
  2. Use the react-router component prop, instead of children.
  3. Only use this.state for data that is changed within a component (i.e. a form input value). If the state is used in multiple components, lift if up to the parent component. If it's used in many components, lift it up to the top (i.e. to your Redux store).

Redux

  1. Consider flattening your state. A good article on this topic can be found here. Example:
const initialState = {
  lists: {
    1: {
      id: '1'
      title: 'List one'
      tasks: ['a', 'b', 'x', 'y'],
    },
    2: {
      id: '2'
      title: 'List two'
      tasks: ['c', z'],
    }
  },
  tasks: {
    a: {
      id: 'a',
      title: 'Important task,
    },
    ...etc
  }
}
  1. Consider using redux-toolkit to reduce boilerplate: https://redux-toolkit.js.org/usage/usage-guide#simplifying-reducers-with-createreducer.

Misc

  1. Beware of mixing package managers (package-lock + yarn.lock). Best to pick one, and stick to it.
  2. Watch out for "unsafe" life-cycle methods: https://reactjs.org/docs/react-component.html#the-component-lifecycle
  3. Consider using a form library. I like https://react-hook-form.com/. Another good option is https://github.com/formium/formik.
  4. Consider learning hooks once you are comfortable with props and state. This is a good skill to have for React jobs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment