React Context API - persist data on page refresh

Cog picture Cog · Nov 24, 2018 · Viewed 30k times · Source

Let's say we have a context provider set up, along with some initial data property values.

Somewhere along the line, let's say a consumer then modifies those properties.

On page reload, those changes are lost. What is the best way to persist the data so we can retain those data modifications? Any method other than simply local storage?

Answer

TLadd picture TLadd · Nov 24, 2018

Yeah, if you want the data to persist across reloads, your options are going to be storing that info server-side (via an api call) or in browser storage (local storage, session storage, cookies). The option you'll want to use depends on what level of persistence you're looking to achieve. Regardless of storage choice, it would likely look something along the lines of

const MyContext = React.createContext(defaultValue);

class Parent extends React.Component {
  setValue = (value) => {    
    this.setState({ value });
  }

  state = {
    setValue: this.setValue,
    value: localStorage.getItem("parentValueKey")
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.value !== prevState.value) {
      // Whatever storage mechanism you end up deciding to use.
      localStorage.setItem("parentValueKey", this.state.value)
    }
  }

  render() {
    return (
      <MyContext.Provider value={this.state}>
        {this.props.children}
      </MyContext.Provider>
    )
  }
}