Things happen outside of React.
It's just a fact of life.
React gives us a single function for connecting to all of the events and effects that React doesn't automatically manage.
It's named React.useEffect()
and you invoke it with a function.
React.useEffect(() => { // doStuff(); })
One of the things we use this function for is fetching data.
React.useEffect(() => { fetchPokemon(1); })
This function will fire every single time the component is rendered.
That includes re-renders by React.useState
.
In our Pokemon app, our "Next" button calls setPokemon()
, re-rendering and re-running our React.useEffect()
function.
function App() { let [index, setIndex] = React.useState(0); let pokemon = collection[index]; return ( <div> <button type="button" onClick={() => setIndex(index + 1)}> Next </button> ... </div> ) }
Give it a try
Use the Code Sandbox below to give this lesson a try directly in the browser.
Assignment
- Call the
React.useEffect()
function in theApp
component - Give
React.useEffect
a function that callsfetchPokemon(index)
for data - Chain a
.then()
ontofetchPokemon(index)
that logs out the returned json
Follow the 🧵 on Twitter:
Subscribe on YouTube:
Top comments (0)