Best Practices for View State

View state has a limit of 135k

Best Practices to optimize your view state

  • Minimize number of forms:
    Avoid using multiple form tag in VF page
    Instead of using multiple forms use <apex:actionregion> to submit portions of the form.
  • Declare variables as Transient.
    if you have referred section view state in VF page you must be aware that non-transient variables are stored.
    If variable is declared as Transient it is not saved and is not transmitted
  • Recreate state instead of storing
    if you can recreate the data during postback using SOQL , you must do that
  • Use Custom settings or Custom objects to store the read only data
  • Only Add the fields in SOQL which is required

View State in VF Page

What is View state:

View state maintains the state of the page by encompassing encrypted and hidden field

HTTP is a stateless protocol which means every request which is being sent and received is an independent request

Example: You filled in a contact form on website and clicked submit, after submitting you might have identified that an error has popped up “your mobile number should have area code” and all the data which you have filled in the form have vanished and you must refill the form again.

This happened because HTTP is stateless protocol and no state was maintained to save that data.

Salesforce encapsulates encrypted and hidden field to hold the state of the page

State includes field values, controller state

 

When Post/Postback is received State view is responsible to recreate the state of the page
It stores following data :

1) All non-transient data members used in the controller and extensions
2) Component tree
3) Small amount of data for VF