Notes

Notes of React Hooks

Edit on GitHub

ReactJS

useEffect()

  • named after side effects, e.g. API calls, manually changing the DOM, setting up a subscription etc.
  • effects happens after every render by default
  • If you need cleanup (i.e. componentWillUnmount), you return a function from your effect function.
  • Use multiple effects to separate concerns
  • Effects are run (all of them) in the order that they are defined
  • cleans up the previous effects before applying the next effects (lesser bugs)
  • You can pass an optional second argument to the effect, an array, which lets you specify what changes to look for when running the effect. If you are using effect to update the count, you’d tell the effect to look for any changes in the state of count, and disregard re-renders because of other changes
1useEffect(() => {
2  document.title = `You clicked ${count} times`;
3}, [count]); // Only re-run the effect if count changes

Example effect

 1useEffect(() => {
 2  function handleStatusChange(status) {
 3    setIsOnline(status.isOnline);
 4  }
 5
 6  ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
 7
 8  // return a function to sepcify how to cleanup after the effect
 9  // you can return a named function for brevity: return function cleanup() {
10  return () => {
11    ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
12  };
13}, [props.friend.id]); // Only re-subscribe if props.friend.id changes