Preserving state across sidebar pages

When a widget is not rendered on a page, its key will get removed from session state. That part is expected. It happens when the Streamlit gets to the end of the page and sees it hasn’t rendered that widget.

If you keep a list of keys associated to widgets that you want to protect, you can keep a global_widget_keys list and put at the top of each page:

for key in 'global_widget_keys':
    st.session_state[key]=st.session_state[key]

This keeps the key ‘alive’ for that page load even if its widget isn’t there. The above mentioned deletion only applies when a key is set to the key optional keyword argument of a widget. That’s because there is an automated cleanup process to remove unused widget keys.

If you declare a key and never assign it to a widget key, it will persist always.

If you declare a key and later assign it to a widget key, it will get captured in the cleanup process and disappear with the widget.