Day120 — React Hooks

Jacky Tsang
2 min readNov 7, 2019

--

Here records the notes I took from reading the React doc. Therefore, most of the stuff is a direct copy.

Motivation

  • Hooks allow you to reuse stateful logic without changing your component hierarchy. (previously, we have patterns like render props and higher-order components to do that)
  • Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data) (previously, componentDidMount method might contain some unrelated logic that sets up event listeners, with cleanup performed in componentWillUnmount. Related logic is split based on lifecycle methods)
  • Hooks let you use more of React’s features without classes. (Class is difficult to understand, especially, this)

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.

Hooks let you organize side effects in a component by what pieces are related (such as adding and removing a subscription), rather than forcing a split based on lifecycle methods.

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. Don’t call Hooks from regular JavaScript functions.

Why useEffect clean up previous effect after every render (before next effect)

This behavior ensures consistency by default and prevents bugs that are common in class components due to missing update logic.

Optimizing Performance by Skipping Effects

If there are multiple items in the array, React will re-run the effect even if just one of them is different.

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. … close to the familiar componentDidMount and componentWillUnmount mental model

--

--

No responses yet