Persisting data in react using local storage

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?

Why do you not want to use state? Normally you would fetch or get the data from LocalStorage and put it in state.

If the component has no state, or no data that is changing, how will it know to re-render? That is besides doing a forced update/re-render.

1 Like

It is something i came across in an article. The article states that data which don’t change as users interact with your app don’t belong in state. I have no practical application of this but i have just been wondering if it is really possible to do it without using state.

Isn’t forceUpdate only applicable in class components?

But how does this apply to a todo app?

The forceUpdate() method yes, but that is why I linked to the search I did. If you look there are ways to force update a function component. But having to force re-render is usually just a sign that something isn’t right.

I guess i just need to take it that it is impossible to achieve what i am thinking about.

Not sure it’s impossible, but just because something is possible doesn’t mean you should do it. I would at least suggest you come up with a good reason why first.

I don’t understand what it is you are trying to achieve here?

1 Like

I have no intention of using it in a project. My interest is to find out whether it is possible or not.