Skip to content
Related Articles

Related Articles

How to save new state to local JSON using ReactJS ?

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 14 Apr, 2021
Improve Article
Save Article

Sometimes we need to store the state locally on the browser in a JSON format. We can save any information to the local storage of the browser and access that information anytime later.

Setting up environment and Execution:

  • Step 1: Create React App by using the following command.

    npx create-react-app foldername
  • Step 2: After creating your project folder, i.e., folder name, move to it using the following command:

    cd foldername

Project Structure: It will look like the following.


import React, { Component }  from 'react';
class App extends Component {
  state = {
    data: "This is data",
    num: 123,
    boolean: true,
  // save data to localStorage
  saveStateToLocalStorage = () => {
    localStorage.setItem('state', JSON.stringify(this.state));
  // Fetch data from local storage
  getStateFromLocalStorage = () => {
    let data = localStorage.getItem('state');
    if(data !== undefined) {
  componentDidMount() {
    // Fetch data from local storage
  render() {
    return (
        <button onClick={this.saveStateToLocalStorage}>
          Save State to local storage\
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!