Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
How to local store a useState data in ReactJs

I have this hook

const [folders, setFolders] = useState([]);

How can I local store this data so when you refresh the page data in useState saves

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

you might store the data in the localStorage, but when you use the setFolders() function, you must update it in localStorage.

Your code should look like this:

const [folders, setFolders] = useState(JSON.parse(localStorage.getItem('folders')) || [])
const setFoldersStorage = (new) => { setFolders(new); localStorage.setItem('folders', JSON.stringify(new)); }

when you want to update folders, you use the setFoldersStorage()

about 4 years ago · Santiago Trujillo Report

0

// Retrieve the initial data from the localStorage
const [folders, setFolders] = useState(
  () => JSON.parse(localStorage.getItem("folders") || "[]"));

// store the value into the localStorage whenever folders is updated
useEffect(() => {
  localStorage.setItem("folders", JSON.stringify(folders));
}, [folders]);

You can also create a custom hook so you can reuse it

function useStateLs(initValue, lsKey) {
  const [value, setValue] = useState(
    () => JSON.parse(localStorage.getItem(lsKey) || JSON.stringify(initValue))
  );
  
  useEffect(() => {
    localStorage.setItem(lsKey, JSON.stringify(value));
  }, [value]);

  return [value, setValue];
}

const [folders, setFolders] = useStateLs([], "folders");
about 4 years ago · Santiago Trujillo Report

0

So mainly, what you need is to set an item to the local storage every time the folders state changes and at the same time update setFolders every time the component re-renders.

  function MyComponent(){
    const [folders, setFolders] = useState([])

      // update setFolders with the local storage data
      useEffect(() => {
        setFolders(JSON.parse(window.localStorage.getItem('folders')))
      }, [])

      // save folders state in local storage when it changes
      useEffect(() => {
        window.localStorage.setItem('folders', folders)
      }, [folders])

    return <>{folders}</>
  }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!