noobling/learn

React

Opened this issue · 0 comments

Hooks

Issues with React that hooks try to solve

  • Render props and higher order components can make code harder to follow
  • React needs a better primitive for sharing stateful logic
  • Confusing with wrapper hell: components surrounded by layers fo providers, consumers, higher-order components, render props and other abstractions
  • Classes confuse both people and machines
    • You have the understand this
    • You have to remember to bind event handlers
    • Code is very verbose e.g. constructor and syntax for class
    • Doesn't minify very well
    • Makes hot reloading flaky and unreliable
    • Harder to optimize

Benefit of hooks

  • Allow you to reuse stateful logic without changing your component hierarchy
  • Lets you split one component into smaller functions based on what pieces are related such as setting up a subscription or fetching data rather than being forced to split it up based on lifecycle methods
  • Lets you use more of React's features without classes
  • React components are closer to functions that classes

Hello world of hooks

https://codesandbox.io/embed/elastic-cache-25k1g

Definition of Hooks

Functions that let you hook into React state and lifecycle features from function components. An example built-in Hook is useState

useEffect

For side effects from a function component. It serves the purpose of componentDidMout, componentDidUpdate, componentWillUnMount but unified into a single API. Runs on every render

Rules of Hooks

  • Only call Hooks at the top level. Don't call Hooks inside loops, conditions or nested functions
  • Only call Hooks from React function components

Stateful logic reuse

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null)

  function handleStatusChange(status) {
    setIsOnline(status.isOnline)
  }

  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange)
    return () => {
       ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange)
  }

  return isOnline
}
function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id)

  if (isOnline === null) return 'Loading...'

  return isOnline ? 'Online': 'Offline'
}
function FriendListItem(props) {
  const isOnline = useFriendStatus(props.friend.id)
  
  return (
  <li style={{ color: isOnline ? 'green' : 'red' }}>
    {props.friend.name}
  </li>
  )
}