Welcome to A Look at React Hooks, a beginner-friendly series on React Hooks. The purpose of this series is to gather and document some awesome Hooks that are not in the official React documentation. Hopefully, by including these Hooks, more developers can know about them and use them.
First, for the beginners, we will explore some common and useful React Hooks then look at the cool custom ones I found. This article serves as a prologue/overview of this series. Let's begin!
What are hooks?
Hooks are available for React packages 16.8.0 or higher. In simple words, hooks are in-built functions that allow developers to use React features such its lifecycle methods, state, props in React functional components.
The naming convention of React Hooks is useSomething
such as useState
, useEffect
, etc. In future articles of this series, you'll see how each of these hooks work and how to use them.
Important things to know
Calling React Hooks
The most important thing to note about Hooks is that they can't be used inside class components. They can only be called in a React function component. Other situations in where Hooks are forbidden to use:
- Inside event handlers
- Inside functions of other Hooks like
useMemo
,useReducer
anduseEffect
- Inside regular JavaScript functions
function Bad1() {
function handleClick() {
// π΄ Bad: inside an event handler (to fix, move it outside!)
const theme = useContext(ThemeContext);
}
// ...
}
function Bad2() {
const style = useMemo(() => {
// π΄ Bad: inside useMemo (to fix, move it outside!)
const theme = useContext(ThemeContext);
return createStyle(theme);
});
// ...
}
class Bad3 extends React.Component {
render() {
// π΄ Bad: inside a class component
useEffect(() => {})
// ...
}
}
Source: reactjs.org/warnings/invalid-hook-call-warn..
Must be called at the top level
When calling Hooks in function components, they must be called at the top level to ensure that they called in the same order at every render.
In other words, they:
- Cannot be inside conditional statements
- Cannot be in loops
- Cannot be in functions
Because that would mean that they may or may not be executed in the same order every time the component renders.
The documentation here provides a detailed explanation on why this must be so.
All in All
In summary, learning React Hooks is not hard at all. As long as we follow its rules and understand how each of them works, we can easily use this amazing React feature in our projects.
Thanks for reading this simple introduction to Hooks. In the next article of this series, we shall take a look at our first Hook: useState
. Stay tuned and cheers!
P.S. Happy Chinese New Year to any chinese readers! ζ°εΉ΄εΏ«δΉοΌ ζεεθ΄’οΌ