Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stats: Introduce LocalStorage helper for cache values #97560

Open
wants to merge 3 commits into
base: trunk
Choose a base branch
from

Conversation

dognose24
Copy link
Contributor

Related to #97336 (comment)

Proposed Changes

  • Introduce the LocalStorageHelper to cache stored period and date range shortcut values, which will prevent frequently fetching items from localStorage when re-rendering.

Why are these changes being made?

  • To avoid frequently getting localStorage item when component re-rendering.

Testing Instructions

  • Spin this change up with the Calypso Live branch.
  • Navigate to Stats > Traffic page.
  • Ensure the stored chart period and date range shortcut still work as previously.
  • Ensure the localStorage getItem access is highly reduced.

Pre-merge Checklist

  • Has the general commit checklist been followed? (PCYsg-hS-p2)
  • Have you written new tests for your changes?
  • Have you tested the feature in Simple (P9HQHe-k8-p2), Atomic (P9HQHe-jW-p2), and self-hosted Jetpack sites (PCYsg-g6b-p2)?
  • Have you checked for TypeScript, React or other console errors?
  • Have you used memoizing on expensive computations? More info in Memoizing with create-selector and Using memoizing selectors and Our Approach to Data
  • Have we added the "[Status] String Freeze" label as soon as any new strings were ready for translation (p4TIVU-5Jq-p2)?
    • For UI changes, have we tested the change in various languages (for example, ES, PT, FR, or DE)? The length of text and words vary significantly between languages.
  • For changes affecting Jetpack: Have we added the "[Status] Needs Privacy Updates" label if this pull request changes what data or activity we track or use (p4TIVU-aUh-p2)?

@dognose24 dognose24 added the [Feature] Stats Everything related to our analytics product at /stats/ label Dec 17, 2024
@dognose24 dognose24 requested review from kangzj and a team December 17, 2024 17:08
@dognose24 dognose24 self-assigned this Dec 17, 2024
@matticbot matticbot added the [Status] Needs Review The PR is ready for review. This also triggers e2e canary tests and wp-desktop tests automatically. label Dec 17, 2024
@matticbot
Copy link
Contributor

matticbot commented Dec 17, 2024

Here is how your PR affects size of JS and CSS bundles shipped to the user's browser:

Sections (~226 bytes added 📈 [gzipped])

name   parsed_size           gzip_size
stats       +686 B  (+0.1%)     +226 B  (+0.1%)

Sections contain code specific for a given set of routes. Is downloaded and parsed only when a particular route is navigated to.

Async-loaded Components (~202 bytes added 📈 [gzipped])

name                                       parsed_size           gzip_size
async-load-store-app-store-stats-listview       +658 B  (+0.6%)     +202 B  (+0.7%)
async-load-store-app-store-stats                +658 B  (+0.3%)     +202 B  (+0.3%)

React components that are loaded lazily, when a certain part of UI is displayed for the first time.

Legend

What is parsed and gzip size?

Parsed Size: Uncompressed size of the JS and CSS files. This much code needs to be parsed and stored in memory.
Gzip Size: Compressed size of the JS and CSS files. This much data needs to be downloaded over network.

Generated by performance advisor bot at iscalypsofastyet.com.

@matticbot
Copy link
Contributor

matticbot commented Dec 17, 2024

This PR modifies the release build for the following Calypso Apps:

For info about this notification, see here: PCYsg-OT6-p2

  • notifications
  • odyssey-stats

To test WordPress.com changes, run install-plugin.sh $pluginSlug update/stats_local_storage_helper on your sandbox.

Copy link
Contributor

@a8ck3n a8ck3n left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit leery of using a Singleton if it can be avoided but I'm not sure what best practice would be in React. I do think we could probably handle this with standard useState() hooks though. What do you think about the approach here?

https://stackoverflow.com/questions/71402674/whats-the-best-way-to-set-localstorage-in-react

I'd also like it if the state was kept together in a single object. I think that makes it easier to inspect/debug and delete if needed. We know it goes together if it's recorded as a single object in storage.

@dognose24
Copy link
Contributor Author

dognose24 commented Dec 20, 2024

handle this with standard useState() hooks though

That would be a concise approach if our LocalStorage usages were all located in functional components. However, we still use the hybrid React approaches.

return this.cache.get( key );
}

const value = localStorage.getItem( key );
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we probably handle the possible exceptions here to make it more robust?

}
}

export default LocalStorageHelper.getInstance();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feels like the singleton is not necessary here as all references would be actually the same object even it'd be imported in several places.

Should the following code do the same?

export default new LocalStorageHelper();

@kangzj
Copy link
Contributor

kangzj commented Dec 23, 2024

I shamelessly asked ChatGPT about it. Here's its recommended solution, which makes sense to me 😄

import { useState, useEffect } from 'react';

const useLocalStorage = (key, initialValue) => {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error('Error reading localStorage key:', key, error);
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error('Error setting localStorage key:', key, error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
};

export default useLocalStorage;
import React from 'react';
import useLocalStorage from './useLocalStorage';

const MyComponent = () => {
  const [value, setValue] = useLocalStorage('myKey', '');

  return (
    <div>
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        placeholder="Type something..."
      />
    </div>
  );
};

export default MyComponent;

return null;
}

public setItem( key: string, value: string ): void {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we might want to serialize the value and provide a more general interface with for example, JSON.stringify.

@dognose24
Copy link
Contributor Author

I shamelessly asked ChatGPT about it. Here's its recommended solution

@kangzj Thanks for the suggestion. Is there a way to apply the solution you mentioned to our Traffic site.jsx as it is a classical React component?

@@ -0,0 +1,46 @@
class LocalStorageHelper {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The helper is useful even with the approach suggested by AI, so I think it still makes sense to address the feedback and move it forward 🙂

Copy link
Contributor Author

@dognose24 dognose24 Dec 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's its recommended solution

The state passing from the hook is not updated when the state is set to a new value. The value remains the original state even after setValue is executed. The saved preference will be applied until a whole page reloads.

2024-12-31.3.08.17.mov

@dognose24
Copy link
Contributor Author

I do think we could probably handle this with standard useState() hooks though

After tackling some code to experiment with the concept, the state would not be shared between components applying the hook, which would remain the original value until the next initiation of the parent component. cc @a8ck3n @kangzj

@dognose24
Copy link
Contributor Author

asked ChatGPT about it. Here's its recommended solution, which makes sense to me

The state passing from the hook is not updated when set to a new value. The value remains original even after setValue is executed. The saved preference will be applied until the whole page reloads.

2024-12-31.3.08.17.mov

You can reproduce the behavior in the recoding using this branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Feature] Stats Everything related to our analytics product at /stats/ [Status] Needs Review The PR is ready for review. This also triggers e2e canary tests and wp-desktop tests automatically.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants