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 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-get-post

v3.0.0

Published

A simple React hook for GETting and POSTing data

Readme

react-get-post

A lightweight and powerful React hook library for data fetching with GET and POST operations. Features built-in caching, loading states, error handling, optimistic updates, and race condition prevention.

npm version License: MIT

Features

  • 🚀 Simple & Intuitive - Easy-to-use hooks for common data fetching patterns
  • 🎯 TypeScript Support - Full TypeScript support with proper type inference
  • 💾 Built-in Caching - Automatic response caching across component instances
  • Optimistic Updates - Instant UI updates with automatic rollback on errors
  • 🔄 Auto Retry - Intelligent retry logic for failed requests
  • 🛡️ Race Condition Safe - Built-in epoch system prevents stale data updates
  • 🎛️ Flexible Configuration - Customizable getter/poster functions and options
  • 📦 Lightweight - Minimal dependencies, only requires React

Installation

npm install react-get-post

Quick Start

Basic GET Request

import { useGet } from 'react-get-post'

function UserProfile({ userId }: { userId: string }) {
  const { data, isGetting, error } = useGet<User>(`/api/users/${userId}`)

  if (isGetting) return <div>Loading...</div>
  if (error) return <div>Error: {error.message}</div>

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

Basic POST Request

import { usePost } from 'react-get-post'

function CreateUser() {
  const { isPosting, error, post } = usePost<Partial<User>, User>('/api/users', { getUrl: '/api/users' })

  const handleSubmit = async (userData: Partial<User>) => {
    await post(userData)
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* form fields */}
      <button disabled={isPosting}>
        {isPosting ? 'Creating...' : 'Create User'}
      </button>
      {error && <div>Error: {error.message}</div>}
    </form>
  )
}

API Reference

useGet<T>(url: string, options?: GetOptions)

Hook for GET requests with automatic caching and loading states.

Parameters

  • url - The endpoint URL to fetch from
  • options - Optional configuration object

Options

interface GetOptions {
  getter?: (url: string) => Promise<T>  // Custom fetch function
  query?: Record<string, string>        // Query parameters
  keepPreviousData?: boolean           // Maintain previous data while refetching
}

Returns

{
  data: T | null        // The fetched data
  isGetting: boolean    // Loading state
  error: Error | null   // Error state
}

Example

const { data, isGetting, error } = useGet<User[]>('/api/users', {
  query: { page: '1', limit: '10' },
  keepPreviousData: true
})

usePost<TRequest, TResponse>(url: string, options?: PostOptions<TRequest, TResponse>)

Hook for POST requests with optimistic updates and automatic data synchronization.

Parameters

  • url - The endpoint URL to post to
  • options - Optional configuration object

Options

interface PostOptions<TRequest, TResponse> {
  poster?: (url: string, body: TRequest) => Promise<TResponse>  // Custom post function
  query?: Record<string, string>                                // Query parameters for POST
  getUrl?: string                                               // The GET endpoint to refresh/sync after successful POST
  getterQuery?: Record<string, string>                          // Query parameters for GET refresh
  optimisticData?: TResponse | ((value: TResponse, request?: TRequest) => TResponse)  // Optimistic update data
  useResponseData?: boolean                                     // Use POST response for data update
}

Returns

{
  data: TResponse | null                                    // Response data from POST
  isPosting: boolean                                       // Loading state
  error: Error | null                                      // Error state
  post: (body: TRequest, extraOptions?: PostOptions<TRequest, TResponse>) => Promise<void>  // Post function
}

Example with Optimistic Updates

const { post, isPosting } = usePost<Partial<User>, User>('/api/users', {
  getUrl: '/api/users',
  optimisticData: (users: User[]) => [...users, newUser],
  useResponseData: true
})

const handleCreate = async (userData: Partial<User>) => {
  await post(userData)
}

triggerGet(url: string, options?: GetOptions)

Manually trigger a GET request for a specific URL. Useful for refreshing data from outside components.

Example

import { triggerGet } from 'react-get-post'

// Refresh user data from anywhere in your app
triggerGet('/api/users', { query: { page: '1' } })

Advanced Usage

Custom Fetch Functions

import { useGet, usePost } from 'react-get-post'

const customGetter = async (url: string) => {
  const response = await fetch(url, {
    headers: { 'Authorization': `Bearer ${token}` }
  })
  return response.json()
}

const { data } = useGet('/api/protected', { getter: customGetter })

Optimistic Updates with Rollback

const { post } = usePost<Partial<Todo>, Todo>('/api/todos', {
  getUrl: '/api/todos',
  optimisticData: (todos: Todo[]) => [
    ...todos,
    { id: Date.now(), text: 'New todo', completed: false }
  ]
})

// If the POST fails, the optimistic update is automatically rolled back
await post({ text: 'New todo', completed: false })

Data Persistence Across Components

// Component A
const { data } = useGet<User>('/api/user', { keepPreviousData: true })

// Component B (mounted later) - instantly gets cached data
const { data } = useGet<User>('/api/user', { keepPreviousData: true })

Error Handling

The library includes built-in error handling and retry logic:

  • Automatic Retry: Failed requests are automatically retried after 1 second if no data exists
  • Race Condition Prevention: Epoch system ensures only the latest request updates the state
  • Optimistic Rollback: Failed optimistic updates are automatically rolled back

TypeScript Support

Full TypeScript support with generic type parameters:

interface User {
  id: number
  name: string
  email: string
}

const { data } = useGet<User>('/api/user/1')  // data is typed as User | null
const { post } = usePost<Partial<User>, User>('/api/users', { getUrl: '/api/users' })

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see the LICENSE.md file for details.

Author

stagas