What is view state in Visualforce

What is view state in Visualforce? In short, it makes Visualforce page appears stateful. If you were like me who were not very clear about the difference between stateful and stateless, you might feel similarly confused. What the hell does that mean?

It is easier to be understood with a simple example:

Visualforce page:

<apex:page controller="SampleViewStateController">
        <apex:commandButton value="click me" action="{!sampleButtonClick}"/>

Controller code:

public class SampleViewStateController 
    public Integer testNumber;
    public SampleViewStateController()
        testNumber = 10;
    public pageReference sampleButtonClick()
        System.debug('test Number is: ' + testNumber);
        return null;

There is no surprise the result is 10. However, is that truly no surprise at all? How does Salesforce remember the value of testNumber?

Please note, the controller’s constructor code is run during the initialization of the page. And sampleButtonClick() code is only fired when the button is clicked. There is no way they are in the same execution context. So the heap which stored the value of testNumber is long gone. How does the server remember it?

The fact that server seems to be able to remember is values is stateful. Actually, the server doesn’t remember them. It only pretends to be – by using view state.

So what does view state contains?

Here is the explanation from Salesforce:

The data in the view state should be sufficient to recreate the state of the page when the postback is received. To do this, it stores the following data:

  • All non-transient data members in the associated controller (either standard or custom) and the controller extensions.

  • Objects that are reachable from a non-transient data member in a controller or controller extension.

  • The component tree for that page, which represents the page’s component structure and the associated state, which are the values applied to those components.

  • A small amount of data for Visualforce to do housekeeping.

A little bit from my understanding:

Basically there are two parts you need to worry about:

  1. The data need to be kept in the apex controller.
  2. The amount of data for Visualforce to do housekeeping. The amount is actually not small.

I don’t need to explain too much about the first one.

The second part of data contains the data for initial setup and the maintenance of <apex:xxx> tags. Essentially every <apex:xxx> tag inside <apex:form> will need to store some data into view state.

How much does each one cost? And what is the best practice to reduce them? I will explain in more details in upcoming posts.

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

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