How statefull property used with JS file in magento 2?

One of the useful Magento statefull properties from the UI module element js used to save state in 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 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,

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,

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 reload 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: {}

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

A statefull property Magento

Save value in local storage with property name appData object.