
Using routing in React
In this article, I demonstrate how to use React Router to navigate between multiple pages without ever reloading the browser. I explain the steps to install the library, configure the BrowserRouter, and define clear routes for components like the homepage or the "About" page. Finally, I present the use of the Link tag to create a smooth and interactive navigation bar.
Introduction to Hooks in React
In the last blog post, we explored components in React and how props allow us to pass data. Today, we'll delve into an important and very useful concept for managing state and effects in React applications: Hooks.
1. What is a Hook in React?
Hooks are functions that allow you to use state and other React features within functional components. Before their introduction in version 16.8, only class components could manage state. With Hooks, functional components have become more powerful and easier to write.
Here are some common Hooks:
-
useState: Allows you to manage local state within a component.
-
useEffect: Used to manage side effects (such as API calls or DOM updates).
-
useContext: Used to access a global context without passing props.
-
useRef: Allows direct access to a DOM element.
Today we'll focus on useState and useEffect with simple examples.
2. Using useState
useState allows you to add local state to a functional component. Here's a simple example:
1import React, { useState } from 'react';
2
3function Counter() {
4
5const [counter, setCounter] = useState(0);
6
7return (
8
9<div>
10<p>Counter value: {counter}</p>
11<button onClick={() => setCounter(counter + 1)}>Increment</button>
12
13</div>
14
15);
16
17}
18
19export default Counter;
20In this example:
-
useState(0)initializes acounterstate with the value 0. -
setCounteris a function that updates the value ofcounter. -
A button increments the counter with each click.
3. Using useEffect
useEffect allows you to execute code after the component has rendered. It is often used for API calls or updating the DOM.
Example:
1import React, { useState, useEffect } from 'react';
2
3function Clock() {
4
5const [time, setTime] = useState(new Date().toLocaleTimeString());
6
7useEffect(() => {
8
9const interval = setInterval(() => {
10
11setHeure(new Date().toLocaleTimeString());
12
13}, 1000);
14
15return () => clearInterval(interval);
16
17}, []);
18
19return <h2>It is {time}</h2>;
20
21}
22
23export default Clock;
24Explanation:
-
useEffectcreates an interval that updates the time every second. -
The function returned by
useEffect(clearInterval) is executed when the component is unmounted to prevent it from running indefinitely. -
The
[]in the second argument means the effect runs only once after the first render. We could add a state to listen for so the effect runs on every change.
4. Creating a Custom Hook: useFetch with PokeAPI
Custom hooks allow you to reuse specific logic while saving lines of code. We'll create a useFetch hook that retrieves data from an API and displays it.
In this example, we'll use PokeAPI to create a mini Pokédex.
Creating the useFetch.js Hook
1import { useState, useEffect } from 'react';
2
3function useFetch(url) {
4const [data, setData] = useState(null);
5
6const [loading, setLoading] = useState(true);
7
8const [error, setError] = useState(null);
9
10useEffect(() => {
11fetch(url)
12.then((response) => response.json())
13.then((data) => {
14setData(data);
15setLoading(false);
16})
17.catch((err) => {
18setError(err);
19setLoading(false);
20});
21}, [url]);
22
23return { data, loading, error };
24}
25
26export default useFetch;Using the Hook in an App.js component
1import './App.css';
2import { PokemonDetails } from './components/PokemonDetails';
3import useFetch from './hooks/usefetch';
4import { useState } from 'react';
5
6function App() {
7const [name, setName] = useState('');
8const { data } = useFetch('https://pokeapi.co/api/v2/pokemon/'+name);
9
10return (
11
12<div className="App">
13
14<div className='pokedex-content'>
15
16{data && <PokemonDetails data={data} />}
17
18<form>
19
20<label>Pokémon number or name</label>
21
22<div className='input-group'>
23
24<input onChange={(e) => setNom(e.target.value.toLowerCase())} type='text' placeholder='Search for a Pokémon' />
25
26</div>
27
28</form>
29
30</div>
31
32</div>
33
34);
35
36}
37
38export default App;
39What happens in PokemonDetails.js
1import React from 'react';
2
3export const PokemonDetails = ({ data }) => {
4return(
5<div className="pokemon-details">
6<div className="pokemonScreen">
7<img src={data.sprites.versions['generation-v']['black-white'].animated.front_default} alt={data.name} />
8<h3>{data.name.charAt(0).toUpperCase() + data.name.slice(1)}</h3>
9</div>
10</div>
11);
12}Preview
 {
2
3return (
4<div>
5<h1>My React Application</h1>
6<Routes>
7<Route path="/" element={<Home />} />
8<Route path="/about" element={<About />} />
9</Routes>
10
11</div>
12
13);
14
15}
16
17export default App;
18Here, we define two pages: Home for the home page (/) and About for the "About" page (/about).
Create the page components
Create two quick and simple components in the Home.js and About.js files.
- In
src/, create a file namedHome.jsand add:
1function Home() {
2return <h2>Welcome to the home page!</h2>;
3
4}
5
6export default Home;
7- In
src/, create a file namedAbout.jsand add:
1function About() {
2return <h2>About this app</h2>;
3
4}
5
6export default About;
7Add Navigation
To easily navigate between our pages, we'll add links.
- Modify
App.jsby adding these imports:
1import { Link } from 'react-router-dom';
2- Add these links before
<Routes>:
1<nav>
2<Link to="/">Home</Link> | <Link to="/about">About</Link>
3The complete App.js file should look like this:
1import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
2
3import Home from './Home';
4
5import About from './About';
6
7function App() {
8
9return (
10<Router>
11<div>
12<h1>My React App</h1>
13<nav>
14<Link to="/">Home</Link> | <Link to="/about">About</Link>
15</nav>
16<Routes>
17<Route path="/" element={<Home />} />
18<Route path="/about" element={<About />} />
19</Routes>
20
21</div>
22
23</Router>
24
25);
26
27}
28
29export default App;
30Now, when you click on "Home" or "About", the page changes without reloading.
Conclusion
There you have it. We've implemented a navigation system in React with React Router. Now we can add more pages and improve our application by making it more interactive.
Sources
-
W3Schools. (n.d.). React Router. Accessed March 1, 2025, at https://www.w3schools.com/react/react_router.asp
-
Ndaw, I. (February 17, 2020). The Complete Guide to React Router. Ibrahima Ndaw. Accessed March 1, 2025, at https://www.ibrahima-ndaw.com/fr/blog/the-complete-guide-to-react-router/
Continue reading


