Hello, explorer! We'll be delving further into React, encountering asynchronous API calls and custom hooks. These tools will enable us to confidently manage states and reuse code.
Asynchronous operations in JavaScript resemble those of a busy astronaut. You'd request supplies (by sending a request) and then proceed with other tasks without waiting for the supplies (response).
The Fetch API is used to send a GET request, as exemplified below:
In React, just as you reuse components through importing, custom hooks allow you to extract and reuse state logic across different components. Custom hooks, just like normal built-in hooks such as useState or useEffect, can hold data throughout component re-renders, triggering rendering updates when the state changes.
Let's create a custom hook named useFetchSpaceships which we'll use to fetch spaceships data:
In the above code:
- We create a function
useFetchSpaceshipswhich takes the URL for our API as a parameter. - We set a state variable
datawhich stores the fetched data, andloadingto keep track of when the data is still being fetched. - We use
useEffectto run our fetch operation once the component mounts. Theurlspecified in the dependency array ensures the operation runs once and subsequently only ifurlchanges. - We fetch the data from the
urland set this data to ourdatastate variable. We also update ourloadingstate to indicate that we've fetched our data. - After the operations are done, we return our
dataandloadingstatus, which can be used in any component to display the fetched data from the API, or show a loading indicator while the data is being fetched.
You've now created your first custom hook! It's all set for incorporation in other components.
