React hooks and why should they get you “hooked” ?

1. Wrapper hell

2. Huge components

3. Confusing classes

Let’s try out various hooks while comparing classes to hooks.

useState

useState “Gotchas.”

  • When we call the function to update the state, it queues a re-render of the component.
  • You can have multiple state variables with useState
  • On the contrary of the previous setState, useState replaces state objects instead of merging them.
  • If you are using an object as state, when you are setting state, you can spread the state to avoid losing properties.

useEffect

  • On render subscribeToStore
  • On component unmount unsubscribeFromStore

useEffect “Gotchas.”

  • If no dependencies array is passed the effect will run every re-render
  • You can return a function from our effect — it will be doing the clean up.
  • If an empty dependencies array is passed we aren’t watching any changes so the effect will only run on the first render.
  • Try avoiding objects in the dependencies array as if they aren’t memoized then the references will change on every re-render forcing that effect to run unexpectedly.

useContext

useContext “Gotchas.”

  • Component that is subscribed to the changes of context re-renders when any of the context values change (as you would expect).

Some more less used hooks

useRef

useMemo

useCallback

Rules of Hooks

Call Hooks only at the top level

A Hook name must start with “use”

A Hook must be called from a function component or from another Hook

Thanks for reading!

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Enemy Set Up — Movement

Gatsby & WordPress — Bringing together the best of a CMS and an SSG

This is the interactive GraphiQL playground after you have installed it in your WordPress dashboard.

CS50 — lab 05 allele and generation

Flask, AJAX, & Bootstrap Tables

Get list of duplicate objects in an array of objects

Structuring React Components for Easy Imports

Use breackpoints as css classes in emotion react

6 Things to Avoid When Learning How to Code

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mindaugas Nakrosis

Mindaugas Nakrosis

More from Medium

Rules of using Hooks in React

What is this React Hooks-Part 2

Components In React

How & when to use redux in react projects?