npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@drepkovsky/nextjs-context

v1.1.1

Published

Here is the revised text with grammar corrections:

Downloads

1

Readme

Here is the revised text with grammar corrections:

Shared Context for NextJS App Router

How to Install

npm install @drepkovsky/nextjs-context # or yarn, pnpm, bun, etc.

How to Use

Create a Shared Context

// theme-context.ts
import { createNextContext } from '@drepkovsky/nextjs-context'

export const [ThemeContextProvider, useThemeContext, fetchThemeContext] = createNextContext(
  'theme', // must be unique for caching and context separation
  async () => {
    const sdk = new MySdk(process.env.NEXT_PUBLIC_API_URL)
    const themeSettings = await sdk.themeSettings.get()
    return { themeSettings }
  }
)

Wrap Your App with the Context Provider

// layout.tsx

import { fetchThemeContext, ThemeContextProvider } from './theme-context'
import type { PropsWithChildren } from 'react'

export default async function RootLayout({ children }: PropsWithChildren) {
  const themeContext = await fetchThemeContext()

  return (
    <html lang='en'>
      <body>
        <ThemeContextProvider value={themeContext}>     
          {children}
          <Button/>
        </ThemeContextProvider>
      </body>
    </html>
  )
}

Usage in Shared Components

// ui/button.tsx

import { useThemeContext } from './theme-context'

export default function Button() {
  const { themeSettings } = useThemeContext()

  return (
    <button style={{ color: themeSettings.color }}>
      Click me
    </button>
  )
}

Now you can use Button in both client and server components without worrying about fetching the theme settings multiple times.

Usage in Client Components

// client/page.tsx

'use client'

import { useThemeContext } from './theme-context'

export default function Page() {
  const { themeSettings } = useThemeContext()

  return (
    <div style={{ backgroundColor: themeSettings.backgroundColor }}>
      <Button/>
    </div>
  )
}

Usage in Async Components

// async/page.tsx

export default async function Page() {
  const { themeSettings } = await fetchThemeContext() // notice that you can't use useThemeContext here

  return (
    <div style={{ backgroundColor: themeSettings.backgroundColor }}>
      <Button/>
    </div>
  )
}

Glossary

  • Shared component: A component that is not marked as async and does not use the use client directive. These components can be imported and used by both client and server async components.
  • Shared context: A context used by shared components, cached on the server and taken from the React.Context API on the client.

Motivation

When trying to prevent 'prop drilling' in NextJS projects that use the quite not-so-new app router, you'll often find yourself in a situation where you need to decide whether you'll wrap each component needing the shared context with the use client directive and use the regular React.Context API or mark every component as an async server component and fetch the context data inside the component itself.

This is not ideal for several reasons:

  1. When using the use client directive, you may be bringing redundant JS to the client, even if no specific client-side logic is happening inside the component.
  2. When marking the component as an async server component, you may be fetching the same data multiple times if you are not caching the responses (NextJS does this automatically for requests using fetch).
  3. When marking the component as async, you may lose the ability to freely compose your components, as you are now unable to import this async component inside a client component or a shared component that can be executed on the client.