React Aims & Objectives 2

What we did last week:

What we're doing today:

New Lifecycle Methods

  • N.B. Most Lifecycle methods are meant to be rarely used. They are to catch edge cases
  • When we 'extends React.Component' - here is a full list of what React's basic component comes with: https://reactjs.org/docs/react-component.html
    • It has all the methods
    • Any starting with UNSAFE_ are just that
    • Pay attention to error handling (covered in error boundaries)

Doing away with the Constructor

  • Under the hood you don't
  • You use a thing called esnext class properties
    • They are transpiled by babel to create the constructor behind the scenes
  • Details and controversy
  • demo

refs

  • Refs are about getting a physical reference to an element in the DOM
  • Refs are not very react-like
  • They should be avoided where possible
  • BUT in some cases they are correct to use:
    1. You've rendered a video into the page and want to set it playing using .play()
    2. You've got a form in the page and you want to focus an input
    • These don't require a re-rendering of a page as they are basic DOM functionality
  • refs demo
  • passing refs from parent components (forwardRef)

Portals

  • NOT really a big thing
  • Used to put data in another part of the page
  • Useful when parent component has its overflow hidden
  • demo

Error Boundaries

  • For optimisation, react throws some weird and obscure errors
  • To be able to see the component tree in the stack trace we create a component called an error boundary and wrap child components in it
  • demo
  • Not to be used for normal try/catch, more for unexpected errors

React Hooks

  • So you don't have to change between class and function when adding/removing state from a component
  • demo

Forms In React

  • Rather than take the values from the DOM we run them through the state.
    • This gives us 'controlled components' whose values are held in the state and can only be updated through the state.
      • Gives an opportunity for validation
      • Means we don't have to serialise the form, just send the data in the state
      • demo of controlled vs uncontrolled
  • A solution like Formik may be better (demo)
    • Forms can be validated at 'form level' (all at once on submission) or field level (as you type)
    • Yup is a great peer dependancy for Formik
  • LATEST WAY: react-hook-form (demo)

React Learning Aims & Objectives 2

By James Sherry

React Learning Aims & Objectives 2

What we're trying to achieve when learning react

  • 1,225