How does Visualforce handle view state?

What is View State?

  • HTTP is Stateless: The Hypertext Transfer Protocol (HTTP) used for web communication is stateless. This means that each request from a web browser to a server is treated as a brand new request, without any memory of previous interactions.
  • Maintaining State: Visualforce pages often need to maintain state between requests. For example, a page might need to remember the values entered in a form or the results of a query.
  • View State as the Solution: Visualforce uses a mechanism called "view state" to preserve this state. It's essentially a snapshot of the page's data and component hierarchy at a particular point in time.


How View State Works :

  1. Serialization: When a Visualforce page is rendered, the framework serializes the relevant data (like component states, field values, and controller variables) into an encrypted string.
  2. Hidden Field: This encrypted string is stored in a hidden form field within the page.
  3. Round Trip: When the user interacts with the page (e.g., clicks a button), the view state is sent back to the server along with the request.
  4. Deserialization: The server deserializes the view state, restoring the page's previous state.
  5. Processing: The server processes the user's action, potentially modifying the data.
  6. Update: The view state is updated to reflect the changes.
  7. Response: The updated page, including the new view state, is sent back to the browser.


Key Considerations :

  • Size Limit: View state has a size limit (currently 135KB). Exceeding this limit will result in an error.
  • Performance: Large view states can impact page load times and performance, as they need to be serialized, transmitted, and deserialized.
  • Security: View state is encrypted to protect sensitive data.


Best Practices for Managing View State :

  • Reduce Data:
    • Use filters and pagination to limit the amount of data displayed on a page.
    • Use the transient keyword in Apex to exclude variables that don't need to be persisted across requests.
    • Optimize SOQL queries to retrieve only necessary data.
  • Minimize Components: Reduce the number of UI components on the page.
  • Use Read-Only Components: Consider using <apex:outputText> instead of <apex:inputField> for displaying non-editable data.
  • Leverage JavaScript Remoting: For certain scenarios, JavaScript remoting can reduce reliance on view state.


Monitoring View State :

  • Development Mode: Enable "Show View State in Development Mode" in your user settings to inspect the view state of a page.
  • Analyze: Use the view state tab in the development mode footer to identify which parts of your page are contributing most to the view state size.

By understanding how Visualforce handles view state and following best practices, you can build efficient and performant Visualforce pages.