Navigation State in React Router
If we click on the products in the list, we see that the first time the product page loads with a delay, and the rest of the time it loads quickly, the same thing when adding and updating a product, since we have a cache on the client side.
In this lesson, we will show the user the state of our page. The hook useNavigation
can help us with this. As a result of its work, this hook produces an object with a number of properties. We will be interested in one of them - the property state
.
The state
property can have 3
values: 'idle'
(nothing happens), 'submitting'
(when the action
route is called when submitting a form via POST, PUT, PATCH or DELETE), 'loading'
(when the loader for the next route is called to render the next page). We'll be interested in the last value.
Let's go into the root.jsx
file and import this hook:
import useNavigation from 'react-router-dom';
Then, for the result returned by the hook, we create a variable navigation
in the function Root
- before return
:
const { products } = useLoaderData();
const navigation = useNavigation();
Now let's use its property state
, if it is the value 'loading'
, then we will set the class loading
for the div in which we are rendering the product data:
<div id="product" className={navigation.state === 'loading' ? 'loading' : ''}>
<Outlet />
</div>
We just need to add styles for the loading
class to index.css
. Let's just increase opacity
in the loading state:
div.loading {
opacity: 0.3;
}
Now, if we reload the site and click on the products in the list or, for example, add a new product, we will see that the current page will fade for a moment before the next one appears.
Take the app you created in the previous lessons. Using the lesson materials, use the useNavigation
hook to make it so the user can see that the next page with student data is loading.