/advanced-react-patterns

Primary LanguageJavaScriptOtherNOASSERTION

What I've learnt

An intro to design patterns in general (which suggests "prefer duplication over the wrong abstraction" and "optimize for change first").

For more details, see src/exercise/*.md files

Latest Ref

  • This pattern allows you to access the latest value of a prop, state, or a callback without needing to list it in the dependency array. It's an intentional replicate of an old default feature of class-based React (which may cause typical asynchronous bugs in some cases, e.g: Imagine, you start the async thing, then props change while that is in flight, when your code continues you'll have the latest values of this.props rather than what you want: the values that existed at the time the function started running adheres to its closure):
function useExampleOne(callback) {
  React.useEffect(() => {
    callback()
  }, [callback]) // <-- have to include the callback in the dep array
}

function useExampleTwo(callback) {
  const {current: latestCallbackRef} = React.useRef(callback)

  React.useLayoutEffect(() => {
  // https://kentcdodds.com/blog/useeffect-vs-uselayouteffect#one-special-case
    latestCallbackRef = callback
  })

  React.useEffect(() => {
    latestCallbackRef()
  }, []) // <-- don't have to include the callback in the dep array
}

Context Module Functions

  • SoC and enhancing reusability, more details at 02:20.
  • Typical use cases at 03:25.

Layout Component

Compound Component

  • Abstracting away the state management of child components to their parent using React.Children and React.cloneElement.
  • Use cloneElement to maintain immutability between renders of child components.
  • Notice (at 1:05) when passing props to a non-functional component (DOM element).
  • Use context to manage state of a compound component with multiple levels of children.
  • Read more.

Prop Collections and Getters

  • Using useRef (at useToggle definition) to secure initialState.
  • Returning objects of props (in the form of returned value from a function) in your custom hook/component so that later you can simply spread across the rendered UI, i.e. composing props. See more at 01:50 and at the returned onClick function in getTogglerProps from Extra Credit.
  • A notice when combining props at 0:50.

State Reducer

  • Using alias to add extra functionality to or replacing an existing function (example at useToggle hook call).

Control props

  • Controlling props by evaluating their use case through an if statement. See more at onIsControlled in the useToggle hook.
  • useRef to get the previous state of the component (at useControlledSwitchWarning hook definition).
  • Set up Dev's warnings (in custom hook) for the misuse of our "controlled" props.
  • Using the & operator (i.e. intersection) to define a generic for a function that takes ...props (checkout getTogglerProps in 06.tsx).