View State is snapshot of values in form, values from controller and the component tree of elements, which associate with variables. In the previous article we discussed how we can look at it directly in your visualforce page. Now, let’s introduce the limits for this view state.

Salesforce allows Visualforce pages to have a maximum view state size of 135KB. In order to avoid this error, you should minimize your pages’ view state. That means, if you receive error message “Maximum view state size limit (135KB) exceeded.” , or you want to load your visualforce page quicker, then follow the rule –  the smallest view state means the faster loading. Then, you can optimize your visualforce page elements and controller.

Visualforce tips /or recommendations:

  • Use only one apex:form element on your page
  • In some cases you can use the second page for proceed data and on the first page use apex:outputLink to this page instead of using apex:commandLink or apex:commandButton components, which need to be in apex:form element
  • Replace apex:inputField with apex:input, this will decrease amount of generated HTML.
  • You can also stop using apex:inputField and apex:input. Instead of it, use html code for input elements <input type=’..’/> and communication with controller will be via remote actions or apex:actionFunction

Controller tips or recommendations:

  • The best recommendation is: Do not store the data you do not need. So you should reduce the number of public variables declared in controller and if it is not possible, you can use ‘transient’ keyword. What will this variable define is that it does not need to be stored in the view state)    However you must be careful because after click on some button, variable will be empty in your controller.  Example: transient public List<Accounts> lstAccounts {get; set;}
  • If you have a lot of data that needs to be shown on the visualforce page only, but you need them also in some methods after click on the button, then do not store them in the view state, the better solution is to reload them again from the database. )
  • Optimize your query to not select fields which you do not need

I hope, it helped you and your pages will now load faster and without exceeding view state limit!