React Docs

React is an open source JavaScript library for building user interfaces, developed by Meta (formerly Facebook) since 2011. Here, I seek to become better acquainted with my poison of choice. Having already covered the previous documentation, the notes below cover the latest (as of March 2023) beta version of the documentation.

Notes are separated into:

  1. Get started

  2. Learn React

My notes are based on documentation distributed by React under the license: Creative Commons Attribution 4.0 International.

Insights

Components must start with capital letters. Rename all component files to begin with capitals.

Always use keys.

Reminder to use square brackets for specifying properties with dynamic names.

Immer is a revelation.

Use reducers. Then, event handlers only specify what happened by dispatching actions, and the reducer function determines how the state updates in reponse to them.

const tasksReducer = (tasks, action) => {
  switch (action.type) {
    case "added": {
      return [
        ...tasks,
        {
          id: action.id,
          text: action.text,
          done: false,
        },
      ];
    }
    case "changed": {
      return tasks.map((t) => {
        if (t.id === action.task.id) {
          return action.task;
        } else {
          return t;
        }
      });
    }
    case "deleted": {
      return tasks.filter((t) => t.id !== action.id);
    }
    default: {
      throw Error("Unknown action: " + action.type);
    }
  }
}

Use contexts.

Use contexts with reducers. The logic can be put into one file.

export TasksProvider = ({ children }) => {
  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);

  return (
    <TasksContext.Provider value={tasks}>
      <TasksDispatchContext.Provider value={dispatch}>
        {children}
      </TasksDispatchContext.Provider>
    </TasksContext.Provider>
  );
}

Cache expensive calculations with useMemo.