Skip to content

Instantly share code, notes, and snippets.

@laneysmith
Last active August 7, 2019 19:21
Show Gist options
  • Select an option

  • Save laneysmith/718d36711c7800c2d7bdc5dc5709817c to your computer and use it in GitHub Desktop.

Select an option

Save laneysmith/718d36711c7800c2d7bdc5dc5709817c to your computer and use it in GitHub Desktop.
react-hooks-notes

useState

  • lets you add state to a functional component
  • state variables can hold objects and arrays; however, unlike this.setState in a class, updating a state variable always replaces it instead of merging it
import React, { useState } from 'react';

const Example = () => {
  // declare a new state variable & initialize it to 0
  // this is the equivalent of setting `this.state` to `{ count: 0 }`
  // in the constructor of a class component
  const [count, setCount] = useState(0);

  return (
    <div>
      // to read state, use `count` directly, since we have no
      // `this` in a functional component
      <p>You clicked {count} times</p>
      // update `count` via `setCount`
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

useEffect

  • lets you perform side effects in function components (e.g., data fetching, setting up a subscription, manually changing the DOM)
  • componentDidMount, componentDidUpdate, and componentWillUnmount combined
  • if your effect returns a function, that function will run on cleanup (componentWillUnmount)
  • accepts an optional second argument, a dependency array
    • if you only want the effect to run on initial render (componentDidMount) and when certain values have changed between re-renders (componentDidUpdate), pass the values in as a second argument
      • React guarantees that setState function identity is stable and won’t change on re-render, so it's safe to omit from the useEffect or useCallback dependency list
    • to run an effect and clean it up only once, on mount and unmount (componentDidMount and componentWillUnmount), pass an empty array
    • to run an effect on every render, don't pass in a second argument at all
React.useEffect(() => {
  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
  
  // function returned below will fun on cleanup
  return () => {
    ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
  };
}, [props.friend.id]); // only re-subscribe if props.friend.id changes

useCallback

  • returns a memoized callback
  • can be used to ensure referential equality between re-renders
  • takes a function as the first arguemnt, takes an optional dependency array as the second argument
  • When to useMemo and useCallback

useMemo

  • returns a memoized value
  • can be used for memoizing computationally expensive calculations
  • takes a function as the first arguemnt, takes an optional dependency array as the second argument

memo

  • React.memo is a higher order component
  • similar to React.PureComponent, but for function components
  • inverse of the shouldComponentUpdate lifecycle method
  • by default it will only shallowly compare complex objects in the props object; if you want control over the comparison, you can provide a custom comparison function as the second argument:
import React, { memo } from 'react';

const MyComponent = (props) => {
  /* render using props */
}

const areEqual = (prevProps, nextProps) => {
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}

export default memo(MyComponent, areEqual);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment