puro
TypeScript icon, indicating that this package has built-in type declarations

0.8.4 • Public • Published

puro - simple react context provider

puro is a react typescript utility library from plasmo to create react context with minimal boilerplate using the react hook API.

Usage

Install

pnpm add puro

Create a provider and hook pairs:

// providers/view-provider.tsx
import { createProvider } from "puro"
import { useContext, useState } from "react"

// A simple example of a provider hook
const useViewProvider = () => {
  const [x, _setX] = useState(0)
  const [y, _setY] = useState(0)

  return {
    x,
    y,
    setX: (newX: string | number) => _setX(parseFloat(newX)),
    setY: (newY: string | number) => _setY(parseFloat(newY))
  }
}

const { BaseContext, Provider } = createProvider(useViewProvider)

export const ViewProvider = Provider

export const useView = () => useContext(BaseContext)

Wrap your top component with the provider, here's a NextJS example using _app.tsx:

// _app.tsx
import type { AppProps } from "next/app"

import { ViewProvider } from "~providers/view-provider"

function CoolApp({ Component, pageProps }: AppProps) {
  return (
    <ViewProvider>
      <Component {...pageProps} />
    </ViewProvider>
  )
}

export default CoolApp

Use the context hook in your component

// components/set-coordinate.tsx
import type { AppProps } from "next/app"

import { useView } from "~providers/view-provider"

export function XInput() {
  const { x, setX } = useView()
  return <input value={x} onChange={(e) => setX(e.target.value)} />
}

export function YInput() {
  const { x, setY } = useView()
  return <input value={y} onChange={(e) => setY(e.target.value)} />
}

Development

Terminal 1:

# install deps
pnpm i

# run dev server
pnpm dev

Terminal 2:

pnpm test

Publish process

  1. Commit any changes to the repository.
  2. pnpm version patch | minor | major
  3. pnpm publish

Support

The Battle Station is open for ambassadors.

License

MIT Plasmo Corp.

Readme

Keywords

Package Sidebar

Install

npm i puro

Weekly Downloads

373

Version

0.8.4

License

MIT

Unpacked Size

7.4 kB

Total Files

6

Last publish

Collaborators

  • louisgv