Hi campers,
I have been wondering about use of localstorage
in react for some time. I understand you don’t need to store data which don’t change as users interact with your app in state. In one of the tutorials, the instructor advises one to make use of the local storage.
Let us say i want to fetch data once from an API after a component is mounted from useEffect
and re-render the component without using state. I still don’t understand how that is achievable. I have the following in mind but the code doesn’t make sense. I want to use localStorage
without using state any where in the component.
import React, { useEffect } from "react";
const url = "https://jsonplaceholder.typicode.com/todos/";
export default function App() {
let todoList = [];
useEffect(() => {
const todos = JSON.parse(localStorage.getItem("todos"));
if (todos) {
todoList.concat(todos);
}
async function fetchTodos() {
const todos = await fetch(url).then((response) => response.json());
todoList.concat(todos);
localStorage.setItem('todos', JSON.stringify(todos))
}
fetchTodos();
}, []);
return (
<div className="App">
<ul>
{todoList.map((todo) => {
return <li key={todo.id}> {todo.title} </li>;
})}
</ul>
</div>
);
}
Clearly what i am doing doesn’t make sense because the component will not re-render and besides i need to pass todoList
as a dependency which will cause an infinite loop. Is there a way of using localStorage
without necessarily using state
for the above example?