The code makes unnecessary API calls because there are two useEffect hooks that both fetch data. The first useEffect runs on mount and fetches data for page 1, while the second useEffect runs whenever the page state changes. This causes two API calls when the component first loads, one from each useEffect. To fix this, you can merge them into a single useEffect that runs when page changes, ensuring the API is only called when needed.
What hints could you share about the source like below (what is wrong with the code?):
import { useState, useEffect } from 'react'; import { createRoot } from "react-dom/client"; const fetchTodos = async (page = 1, items = 10) => { const res = await fetch(`/api/todos?items=${items}&page=${page}`); return res.json(); }; function App() { const [todos, setTodos] = useState([]); const [page, setPage] = useState(1); useEffect(function initialFetch() { fetchTodos(1, 10).then(setTodos); }, []); useEffect( function fetchOnPageChange() { fetchTodos(page, 10).then(setTodos); }, [page] ); return ( <div> <h2>Todo List</h2> <table className="table"> <tbody> <tr className="table__row"> <td className="table__row__cell">Title</td> <td className="table__row__cell">Completed</td> </tr> {todos.map((todo) => ( <tr className="table__row"> <td className="table__row__cell">{todo.title}</td> <td className="table__row__cell">{todo.completed ? "Yes" : 'No'}</td> </tr> ))} </tbody> </table> <button onClick={() => setPage(page - 1)}>Previous</button> <button onClick={() => setPage(page + 1)}>Next</button> </div> ); } const root = createRoot(document.getElementById('app')); root.render(<App />);