Categories
React Answers

How to Use Local Storage with React?

Spread the love

Sometimes, we want to store data on local storage in our React app.

In this article, we’ll look at how tostore data on local storage in our React app.

Use Local Storage with React

We can use the native local storage methods in React.

For instance, we can write:

import React from 'react'

class App extends React.Component {
  constructor(props) {
    super(props);
    const storedClicks = 0;

    if (localStorage.getItem('clicks')) {
      storedClicks = +(localStorage.getItem('clicks'));
    }

    this.state = {
      clicks: storedClicks
    };
    this.click = this.click.bind(this);
  }

  onClick() {
    const newClicks = this.state.clicks + 1;
    this.setState({ clicks: newClicks });
    localStorage.setItem('clicks', newClicks);
  }

  render() {
    return (
      <div>
        <button onClick={this.onClick}>Click me</button>
        <p>{this.state.clicks} clicks</p>
      </div>
    );
  }
}

We get the clicks from local storage if it exists.

Then we parse it if it exists and set that as the initial value of the clicks state.

Then in the render method, we have a button to update the clicks state and the local storage clicks value with the onClick method.

It updates the clicks state.

Also, we update the local storage’s clicks value after that.

Conclusion

We can use the native local storage methods in React.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *