📚 Cheatsheet

Une collection organisée de snippets de code pour accélérer votre développement. Parcourez, recherchez et copiez en un clic.

Snippets 9

Retour
App Router : Data fetching dans un Server Component
Intermédiaire
async function getData() {
  const res = await fetch('...');
  return res.json();
}

export default async function Page() {
  const data = await getData();
  return <main>{/* ... */}</main>;
}
App Router : Désactiver la mise en cache
Intermédiaire
fetch('https://...', { cache: 'no-store' });
App Router : Mise en cache du fetch
Intermédiaire
fetch('https://...', { cache: 'force-cache' }); // Comportement par défaut
App Router : Revalidation temporelle
Avancé
fetch('https://...', { next: { revalidate: 3600 } });
Client-side data fetching avec SWR
Intermédiaire
import useSWR from 'swr';

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

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher);
  // ...
}
getServerSideProps (Server-Side Rendering)
Intermédiaire
export async function getServerSideProps(context) {
  const res = await fetch(`...`);
  const data = await res.json();

  return { props: { data } };
}
getStaticPaths pour routes dynamiques
Avancé
export async function getStaticPaths() {
  return {
    paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
    fallback: false, // can also be true or 'blocking'
  };
}
getStaticProps (Static Site Generation)
Intermédiaire
export async function getStaticProps(context) {
  const res = await fetch(`...`);
  const data = await res.json();

  return {
    props: { data }, // will be passed to the page component as props
  };
}
Incremental Static Regeneration (ISR)
Avancé
export async function getStaticProps() {
  const res = await fetch('...');
  const data = await res.json();

  return {
    props: { data },
    revalidate: 10, // Re-generate the page at most once every 10 seconds
  };
}