Skip to content

Instantly share code, notes, and snippets.

@staydecent
Last active August 30, 2019 21:38
Show Gist options
  • Save staydecent/0a6588cc1068f3bab394abfd3add02e2 to your computer and use it in GitHub Desktop.
Save staydecent/0a6588cc1068f3bab394abfd3add02e2 to your computer and use it in GitHub Desktop.
Hooks

Why migrate from class to hooks?

class is syntactic sugar that abstracts prototypal inheritance, making it appear more familiar to those coming from languages with classical inheritance, but does not actually introduce a classical object-oriented inheritance model.

So, it’s basically a LIE.

React docs recommend AGAINST using inheritance to share functionality anyway

So why did they introduce class based components??

In React, Classes were used as a syntactically convenient way to encapsulate a component and it’s functionality.

Hooks allows us to encapsulate a component and it's functionality within a single function.

useState

// Inside a class component
this.state = { loaded: false }

// ... after some async thing loads
this.setState({ loaded: true }) 

Now with hooks:

// inside a function that returns JSX
const [loaded, setLoaded] = useState(false)

// ... after some async thing
setLoaded(true)

If you use an object or array as a useState value, you need to pass in a new reference to trigger an update.

const [items, setItems] = useState([1, 2, 3])
items.push(4)
setItems(items) // Won't re-render
setItems([...items, 4]) // Does re-render!

useEffect

Most lifecycle class methods can be replaced with useEffect. This hook signifies side-effects -- usually async code that may eventually change state.

The question is not "when does this effect run" the question is "with which state does this effect synchronize with"

useEffect(fn) // all state

useEffect(fn, []) // no state

useEffect(fn, [these, states])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment