Skip to content

Frontend ‐ State Management

Jeremy Asuncion edited this page Sep 13, 2023 · 1 revision

Since the napari hub is a React application, we have a lot of state that needs to be managed throughout different components. This document identifies the different approaches and best practices for managing state in the frontend.

SSR

Server Side Rendering is the process of resolving asynchronous data and rendering a React component to HTML on the server. This allows us to provide the HTML with data to the user on initial load.

Local State

Local state is state stored in React state hooks. This allows us to manage state that is used by only a particular component or hook. Generally we should always use local state hooks until we notice a pattern where we’re sharing it with other components. At that point, it’s good to look into using global state via Context or Valtio.

Context

Context is a mechanism in React that allows us to pass and share data to multiple components in a single component tree. Context is great when we want to share props that are used by multiple components, but it’s not great for managing state that changes over time. This is because Context is more general purpose and so it re-renders the entire component tree on state changes instead of re-rendering only the components that use that state.

Because of this, it’s best to use Context for state that stays mostly constant, whereas Valtio can be used for global state that changes over time.

Valtio

Valtio is a global state management library for React that’s based on the proxy pattern. This allows us to treat state as traditional JavaScript objects that can be modified directly to trigger global state updates.

Valtio should be used over context when we need to manage state that may change over time because context is not well suited for re-rendering nested components. For example, the search page is built using Valtio because users may change the search query, filters, and sort options at any time which would trigger a re-render.