Store React Form Data or State in Local Storage

By Digamber Rawat Last updated on

In this tutorial, we will learn how to store React’s form data or form state in local storage using React life cycle methods. Local storage is handy when it comes to storing the data on the web browser; the good thing about local storage is that data doesn’t remove from the browser unless we remove the browser’s cache. We are going to learn how to use local Storage in React app to store the data on the web browser.

We will create a basic React app, in which we will create a basic user form using Bootstrap 4. In this form, we can define the name, email, and phone number. The unique thing about this form is that even if you refresh the browser, the React form state won’t change. Along with that, we will go over the React life cycle methods to set the Form state in local storage.

Introduction to Web Storage

Let’s understand web storage, and it is used to store data locally on the user’s browser. There are two types of web storage Local and Session storage.

Local Storage – Data is stored in the browser’s memory, and it doesn’t expire even after the browser’s window is closed.

Session storage – Data exists as long as the browser’s window is not closed.

The web storage is handy when you are developing shopping cart, storing user logged-in state, or user preferences.

Local storage is best web storage due to it’s higher storage limit. Following are the local storage methods.

Method Description
setItem() Set values in local storage by using key and value
getItem() Get a value by using the key
removeItem() Delete an item by using key
clear() Clears the storage data

React Local Storage Tutorial with Example

We must install basic React app for local storage demo.

Install React v16+ with Bootstrap 4

First, Install basic React project with Bootstrap 4. Run the following command from your terminal.

npx create-react-app react-local-storage

Get into the React local storage project by using the following command.

cd react-local-storage

Next, install bootstrap 4 project in React app.

npm install bootstrap --save

Next, Import bootstrap.min.css in src/App.js file from node_modules folder:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <h3>React Local Storage Tutorial</h3>
      </div>
    );
  }
}

export default App;

Now, It’s time to run the React app.

npm start

Check the project on following URL: localhost:3000

Create React Component

Create src > components folder and create a component file for storing form data in local storage. Name this file form-data-component.js and paste the following code in it.

import React, { Component } from 'react';

export default class FormDataComponent extends Component {
    render() {
        return (
            <div className="container">
                <form>
                    <div className="form-group">
                        <label>Name</label>
                        <input type="text" className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>Email</label>
                        <input type="email" className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>Phone</label>
                        <input type="tel" className="form-control" />
                    </div>
                    <button type="submit" class="btn btn-primary btn-block">Submit</button>
                </form>
            </div>
        )
    }
}

We created a basic user form using Bootstrap 4. This tiny form has a name, email, and phone number field.

Next, add FormDataComponent file in src/App.js file.

import React, { Component } from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';

import FormDataComponent from './components/form-data.component';

class App extends Component {
  render() {
    return (
      <div className="App">
        <FormDataComponent />
      </div>
    );
  }
}

export default App;

Store React Form State in Local Storage with Life Cycle Methods

In this step we will insert values in the React form and store those values in local storage using localStorage web API and React Js component life cycle methods.

Add the given below code in components/form-data.component.js file:

import React, { Component } from 'react';

export default class FormDataComponent extends Component {

    userData;

    constructor(props) {
        super(props);

        this.onChangeName = this.onChangeName.bind(this);
        this.onChangeEmail = this.onChangeEmail.bind(this);
        this.onChangePhone = this.onChangePhone.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: '',
            email: '',
            phone: ''
        }
    }

    // Form Events
    onChangeName(e) {
        this.setState({ name: e.target.value })
    }

    onChangeEmail(e) {
        this.setState({ email: e.target.value })
    }

    onChangePhone(e) {
        this.setState({ phone: e.target.value })
    }

    onSubmit(e) {
        e.preventDefault()

        this.setState({
            name: '',
            email: '',
            phone: ''
        })
    }

    // React Life Cycle
    componentDidMount() {
        this.userData = JSON.parse(localStorage.getItem('user'));

        if (localStorage.getItem('user')) {
            this.setState({
                name: this.userData.name,
                email: this.userData.email,
                phone: this.userData.phone
            })
        } else {
            this.setState({
                name: '',
                email: '',
                phone: ''
            })
        }
    }

    componentWillUpdate(nextProps, nextState) {
        localStorage.setItem('user', JSON.stringify(nextState));
    }


    render() {
        return (
            <div className="container">
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Name</label>
                        <input type="text" className="form-control" value={this.state.name} onChange={this.onChangeName} />
                    </div>
                    <div className="form-group">
                        <label>Email</label>
                        <input type="email" className="form-control" value={this.state.email} onChange={this.onChangeEmail} />
                    </div>
                    <div className="form-group">
                        <label>Phone</label>
                        <input type="tel" className="form-control" value={this.state.phone} onChange={this.onChangePhone} />
                    </div>
                    <button type="submit" className="btn btn-primary btn-block">Submit</button>
                </form>
            </div>
        )
    }
}
  • Declare the userData variable, in this variable we will store the form’s value from local storage.
  • As you can see, we used the componentDidMount() component life cycle method. This method is best used for defining the state, so we are setting up the form data in the userData variable and checking if the localStorage exists then setting up the form state via local storage.
  • The componentWillUpdate() method triggers before the rendering happens. We are setting up form state in local storage.
  • Define onSubmit=”” event this with this.onSubmit method, this method will trigger when a user clicks on the submit button.
  • In the HTML input field, we define the onChange=”” event with the specific methods these methods will trigger when the value of the filed is being changed. We also pass the value and giving the value using the this.state.

If you enter the value in the React form, then you can check out the user object in browser’s local storage tab. When you refresh or close the browser window even then you won’t loose the form state.

React Local Storage

Conclusion

In this React tutorial, we learned how to store form data or state in local storage using React life cycle methods. I hope you must be understood about local storage to React and using life cycle methods along with that. If this tutorial helped you learn about this specific topic, then must share it with others.

Git Repo

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.