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.
// 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!
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])