A Quick Trick to Preserve State Beyond Component Lifecycle

To preserve some state across navigating out and back to a page, the options we have are:

  • cookies
  • context
  • global variable?
  • page url query
  • component static variable (what this note is about)

The component static variable method feels a bit drafty, I don't know if anybody formally use this. On the flip side, I don't see a problem neither.

Features

  • very quick implementation, no context needed
  • does not pollute global variable
  • does not use page url
  • does not use cookie

While considering:

  • the state is still lost when user reloads the page

Why it works

  • static field is preserved by the component, even if the component is unmounted, the value is memoized by the component's object itself.

Implementation

const LIST_BY = {
  TOPIC: 'topic',
  YEAR: 'date',
};
const DEFAULT_LIST_BY = LIST_BY.TOPIC;
const HomePageListing = () => {
  const [listBy, setListBy] = React.useState(HomePageListing.__preservedListBy || DEFAULT_LIST_BY);
  return <section>
    <Switch 
      onChange={(newListBy) => {
        HomePageListing.__preservedListBy(newListBy);
        setListBy(newListBy);
      }} 
      options={[LIST_BY.TOPIC, LIST_BY.YEAR]}
    />
    {listBy === LIST_BY.TOPIC ? <TopicListing /> : <YearListing />}
  </section>;
};