We have one way to update (or re-render) a component.
It's React.useState
.
When we want to render our component with data we've useEffect
ed from the internet, we need to need a useState
updater function to call.
This is a common pairing of functions where server data is used to update a component:
let [componentData, setComponentData] = React.useState(null);
React.useEffect(() => {
fetchData().then(serverData => setComponentData(serverData));
})
In our Pokemon app, that looks like this:
let [index, setIndex] = React.useState(1);
let [pokemon, setPokemon] = React.useState(null);
React.useEffect(() => {
fetchPokemon(index).then(json => setPokemon(json));
});
Our useEffect
connects us to the outside world — fetching data with JavaScript.
The callback we give to fetchPokemon
calls our useState
updater function when data is ready — updating our component.
Give it a try!
Assignment Sandbox:
Assignment:
- Update the
let pokemon
assignment to get it's value fromReact.useState(null)
- Using destructuring assignment, take the second element of
React.useState
's return (our updater function) andsetPokemon
- Replace
console.log(json)
with a call tosetPokemon(json)
Follow the 🧵 on Twitter:
Subscribe on YouTube: