Custom Hooks
Topic 4 in React Hooks: Tyler McGinnis
Some rules of hooks:
Only call Hooks from the top level of a function component or a custom Hook
Do not call them anywhere else. Don’t call them from a normal function, nor from a class component, nor inside a loop, if statement, or event handler.
EG do not call React.useEffect
inside an if statement or a loop. This is because React relies on the consistency of hooks’ call order to keep track of internal state or references.
Traditionally React didn’t have a great answer to re-using non-visual logic across different components. There were Higher-order components and render props.
The logic isn’t very intuitive, and the impact on the app’s tree structure is not great.
Custom hooks are the answer.
We declare a function starting with use
like useHover
. You can return what you like.
Use cases include using local storage, hovering etc. This is what makes hooks so special.
For example here’s a useFetch hook:
function useFetch (url) {
const [loading, setLoading] = React.useState(true);
const [data, setData ] = React.useState(null);
const [error, setError ] = React.useState(null);
React.useEffect(() => {
setLoading(true);
fetch(url)
.then(res => res.json())
.then(json => {
setData(json);
setError(null);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, [url])
return {
loading,
data,
error
}
}
// use like this:
const {loading, data, error} = useFetch(`${url}`);