Sobes.tech
Middle

Have you worked with SWR? What were the nuances, issues with data relevance?

sobes.tech AI

Answer from AI

Yes, I have worked with SWR (stale-while-revalidate) — this is a React hook for fetching data with automatic caching and updating.

Main nuances and issues with data freshness:

  • Update delay: SWR initially returns cached data (stale), then updates it in the background (revalidate). This can lead to a brief display of outdated information.
  • Conflicts during frequent updates: if data changes very often, a situation may occur where the UI shows outdated data until the re-request is completed.
  • Interval settings: it is important to properly configure the refreshInterval and revalidateOnFocus parameters to balance between data freshness and server load.

Example of usage:

import useSWR from 'swr';

const fetcher = url => fetch(url).then(res => res.json());

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher, { refreshInterval: 30000 });

  if (error) return <div>Loading error</div>;
  if (!data) return <div>Loading...</div>;

  return <div>Hello, {data.name}!</div>;
}

Thus, SWR is well-suited for data that can be shown with a slight delay in updates, but requires attention to settings for time-critical data.