Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use React Context With Local Storage

I am trying to store my array with local storage, but I am not sure how to do it. Also, how would I make it so that with each update in the state, the local storage gets updated at the same time?

Current Code:

import React, { useState, createContext } from 'react';
import { v4 as uuidv4 } from 'uuid';

export const NoteContext = createContext();

export const NoteProvider = props => {

    const [notes, setNotes] = useState([
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
            {id:uuidv4(), message:'asdfffffffffffffffffffffffffffffffffffffff',title:'e', selected:false},
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
    
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
        
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
    
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
    
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false}
    
    ])
    return (
        <NoteContext.Provider value={[notes, setNotes]}>
            {props.children}
        </NoteContext.Provider>
    )

}
like image 996
General Pleather Avatar asked Mar 08 '26 07:03

General Pleather


1 Answers

You can initialize your state from localStorage as well as propagate changes to it using useEffect.

function getInitialState() {
  const notes = localStorage.getItem('notes')
  return notes ? JSON.parse(notes) : []
}

export const NoteProvider = props => {
  const [notes, setNotes] = useState(getInitialState)

  useEffect(() => {
    localStorage.setItem('notes', JSON.stringify(notes))
  }, [notes])
}
like image 79
Mark Skelton Avatar answered Mar 10 '26 01:03

Mark Skelton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!