01 February, 2019

TIL #9 - React and apollo

Notes taken between: 28-01 January/February 2019


React

  • Aim at making your components stateless.
  • Remove cognitive load by favouring props over state.
  • Portal brings things up the state.

What is “Mounting” in React?

The main job of React is to figure out how to modify the DOM to match what the components want rendered on the screen (virtual dom)

React does so by "mounting" (adding nodes to the DOM), "unmounting" (removing them from the DOM), and "updating" (making changes to nodes already in the DOM).

How a React node is represented as a DOM node and where and when it appears in the DOM tree is managed by the top-level API.

PureComponent is exactly the same as Component except that it handles theshouldComponentUpdate method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

Stateless Component

Declared as a function that has no state and returns the same markup given the same props.

A quote from the React documentation:

These components must not retain internal state, do not have backing instances, and do not have the component lifecycle methods. They are pure functional transforms of their input, with zero boilerplate. However, you may still specify .propTypes and .defaultProps by setting them as properties on the function, just as you would set them on an ES6 class.

class Welcome extends React.PureComponent {

  render() {
    return <h1>Welcome</h1>
  }
}

Hello = () => {
  return <h1>Hello</h1>;
}

So above there is an example of a very simple Welcome Pure Component and Hello Stateless Component. When you use these two in your Parent Component, you will see Hello will re-render whenever Parent Component will re-render but Welcome Component will not.

This is because PureComponent changes the life-cycle method shouldComponentUpdate and adds some logic to automatically check whether a re-render is required for the component. This allows a PureComponent to call the method render only if it detects changes in state or props.

Apollo

Apollo Client is the leading JavaScript client for GraphQL.

The react-apollo/test-utils module exports a MockedProvider component which simplifies the testing of React components by mocking calls to the GraphQL endpoint. This allows the tests to be run in isolation and provides consistent results on every run by removing the dependence on remote data.

Unexpected token

Network error: Unexpected token < in JSON at position 0 tends to mean HTML is being returned instead of JSON, usually because of redirect due to being unauthenticated or unauthorised. Could also be caused by fetch not sending cookies, which it does not do by default in some older browser versions.