React hooks
React hooks
How
Why
What
What
Hooks are a way to share stateful logic between React components
Hooks are functions that will work exclusively with function components
Class components are becoming obsolete, yet still supported
What are hooks?
Simpler to read and maintain
Favours composition over inheritance
No need for binding anymore
Scalable syntax
The next step from previous patterns like
HOC, Render Props or Mixins
* Which leads to “wrapper-hell” in complex components over time
Why
Advantages of
Function components + hooks
Easier to share and reuse stateful logic
between components
Use hooks only in React function components
Cannot be used as regular functions since they need to be part of the component lifecycle
Only Call Hooks at the Top Level
Cannot be called from within loops or conditional statements
All hooks names should start with "use"
convention to differentiate them from regular functions
Ground rules
How
How
useState()
How
useState()
How
useState()
How
How
How
useEffect()
Handles "side effects" - anything that causes changes outside of rendering your component to the dom
For example: fetching data, handle keyboard or scroll events, set timers etc...
Used as the equivalent to componentDidMount
componentDidUpdate
componentWillUnmount
How
Other built in hooks
useRef()
- reference dom elements
- Instance variables in class components are useRef in hooks
useContext()
- Makes using the Context Api so easy,
some use it for global app state management...
useCallback() , use Memo()
- memoization of functions and UI
useReducer()
- used for more complex component state
should be familiar to anyone who knows Redux
How
Demo time!
React hooks
By Yariv Gilad
React hooks
- 735