First, what's a Hook?
Hooks are the use
-prefixed functions that we've been using — useState
and useEffect
.
Components are the primary building block of React.
Hooks are what give Components interactivity.
Hooks are composable
We've seen that hooks can be used together to accomplish discreet tasks.
let [componentValue, setComponentValue] = useState(null);
React.useEffect(() = {
fetchNetworkValue(query).then(networkValue => setComponentValue(networkValue));
})
You can make your own Hooks
Hooks can be extracted into functions just like Components.
function useRequest(query) {
let [componentValue, setComponentValue] = useState(null);
React.useEffect(() = {
fetchNetworkValue(query).then(networkValue => setComponentValue(networkValue));
})
return componentValue;
}
When we extract custom Hooks, we need to add the inputs and the outputs.
Inputs we take as function arguments.
Outputs we return
from the function.
In the example above, we take query
as a function argument and return componentValue
.
The power is yours
You're not limited to one argument and return.
You can take many arguments and return any data type.
Explore! The world of Hooks is yours.
Try it out!
Open this Code Sandbox in your browser and explore custom Hooks.
Assignment Sandbox:
Assignment
- Declare a new function named
usePokemon
- Take
index
as an argument - Move the pokemon
useState(null)
hook anduseEffect()
Hooks into the body of that function - Return
pokemon
from that function - In App, call the new Hook
usePokemon(index)
and assign it's return to the variablepokemon
You've just made a custom Hook!
Follow the 🧵 on Twitter:
Subscribe on YouTube:
Top comments (0)