How statefull property used with knockout JS to keep form data without losing on reload Magento 2?

Magento 2 Keep form data without losing it on reloading the page, One of the useful Magento statefull properties from the UI module is used to save the state in the local storage of the browser.

A statefull object is used to set the state of the property.

You can see statefull: {} defined under the defaults object from the vendor/magento/module-ui/view/base/web/js/lib/core/element/element.js

Let’s take an example,
We will create a form with an input field and once you enter any value to that field and refresh the page, Your custom value will be removed and the field will be empty or display the predefined value for that input field.

If you want to keep the entered value in the text field after the page load, you need to use statefull property in Magento 2.

Let’s create a simple phtml file and define your custom component using a script tag,

<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app" : {
                "components" : {
                    "saveInputFieldOnPageReload" : {
                        "component" : "Jesadiya_Blog/js/input-state-save"
                    }
                }
            }
        }
    }
</script>
<div data-bind="scope: 'saveInputFieldOnPageReload'">
    <span>Your Name</span>
    <input type="text" name="text" data-bind="value: name"/>
</div>

Here we have defined a custom component called saveInputFieldOnPageReload and we have to define this component in the scope using data-bind.

Now create a js file,
app/code/Jesadiya/Blog/view/frontend/web/js/input-state-save.js

define(['uiComponent'], function (Component) {
    'use strict';

    return Component.extend({
        defaults: {
            tracks: {
                name: true
            },
            statefull: {
                name: true
            },
            name: 'Enter your name'
        }
    });
});

Here By Default, our custom variable name is defined in the input field and once you change the name, you are adding Rakesh as a name in the field and reloading the page, the input value will be Rakesh instead of the default value.

To preserve the name in the input field, you must have to declare that property or variable as observable.

We must have to declare property observable using tracks: {} and define stateful property using statefull: {}

tracks: {
    name: true
},
statefull: {
    name: true
}

You can check the saved value from the local storage of your browser with the inspect element and click on the Application tab.

statefull
A statefull property Magento

Save value in local storage with property name appData object.

appData: saveInputFieldOnPageReload: {name: "rakesh"}