Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/wwwroot/lib/functions.php on line 286

Warning: file_get_contents(https://ghapi.huchen.dev/repositories?since=daily): failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/wwwroot/lib/functions.php on line 286
react-query - Readme

Recent Trend

rotate
Create recursive image rotation animations
Keiko-Corp
HTML challenge for Hacktoberfest 2020
framework

cortex
A horizontally scalable, highly available, multi-tenant, long term Prometheus.
trojan-go
Go实现的Trojan代理,支持多路复用/路由功能/CDN中转/Shadowsocks混淆插件,多平台,无依赖。A Trojan proxy written in Go. An unidentifiable mechanism that helps you bypass GFW. https://p4gefau1t.github.io/trojan-go/
DataStructures-Algorithms
The best library for implementation of all Data Structures and Algorithms - Trees + Graph Algorithms too!
mlbook
Repository for the free online book Machine Learning from Scratch (link below!)
EssayKiller_V2
基于开源GPT2.0的初代创作型人工智能 | 可扩展、可进化
hetty
Hetty is an HTTP toolkit for security research. It aims to become an open source alternative to commercial software like Burp Suite Pro, with powerful features tailored to the needs of the infosec and
fission
Fast and Simple Serverless Functions for Kubernetes
Few-Shot-Patch-Based-Training
The official implementation of our SIGGRAPH 2020 paper Interactive Video Stylization Using Few-Shot Patch-Based Training
raspi3-tutorial
Bare metal Raspberry Pi 3 tutorials
DS-Algo-Point
This repository contains codes for various data structures and algorithms in C, C++, Java, Python.
chibicc
A small C compiler
awesome-for-beginners
A list of awesome beginners-friendly projects.
first-contributions
?✨ Help beginners to contribute to open source projects
ajour
A World of Warcraft addon manager written in Rust.
open-project-1
Unity Open Project #1: Action-adventure
CPP
Repository for C++/C codes and algos.Star the repo too.
PySyft
A library for answering questions using data you cannot see
zhaopp
一个Google Drive搜索引擎 https://zhao.pp.ua/
imaginaire
NVIDIA PyTorch GAN library with distributed and mixed precision support
datasets
? Fast, efficient, open-access datasets and evaluation metrics for Natural Language Processing and more in PyTorch, TensorFlow, NumPy and Pandas
proshop_mern
Shopping cart built with MERN & Redux
puma
A Ruby/Rack web server built for concurrency
kubebuilder
Kubebuilder - SDK for building Kubernetes APIs using CRDs
csharplang
The official repo for the design of the C# programming language
DevUtils-app
Developer Utilities for macOS
elsa
❄️ Elsa is a minimal, fast and secure runtime for Javascript and Typescript written in Go
Flutter-AI-Rubik-cube-Solver
Flutter-Python rubiks cube solver.
jukebox
Code for the paper "Jukebox: A Generative Model for Music"
azure-cli
Azure Command-Line Interface
terraform-aws-vpc
Terraform module which creates VPC resources on AWS
MEDUZA
A more or less universal SSL unpinning tool for iOS
vuetify
? Material Component Framework for Vue
scripts
京东薅羊毛工具(活动入口:京东app->我的->游戏与互动->查看更多)讨论组:https://t.me/JD_fruit_pet
kubeedge
Kubernetes Native Edge Computing Framework (project under CNCF)
hacktoberfest-swag-list
Multiple companies give out swag for Hacktoberfest, and this repo tries to list them all.
visx
? visx | visualization components
CyberChef
The Cyber Swiss Army Knife - a web app for encryption, encoding, compression and data analysis
winget-cli
Windows Package Manager CLI (aka winget)
ts-sql
A SQL database implemented purely in TypeScript type annotations.
azure-sdk-for-js
This repository is for active development of the Azure SDK for JavaScript (NodeJS & Browser). For consumers of the SDK we recommend visiting our public developer docs at https://docs.microsoft.com/en-
cool-retro-term
A good looking terminal emulator which mimics the old cathode display...
rocketmq
Mirror of Apache RocketMQ
Hippy
A cross platform framework designed for Web developer. Introduction video - https://v.qq.com/x/page/i3038urj2mt.html
Tinyhttpd
Tinyhttpd 是J. David Blackstone在1999年写的一个不到 500 行的超轻量型 Http Server,用来学习非常不错,可以帮助我们真正理解服务器程序的本质。官网:http://tinyhttpd.sourceforge.net
ta-lib
Python wrapper for TA-Lib (http://ta-lib.org/).
GNNPapers
Must-read papers on graph neural networks (GNN)
Impostor
Impostor - An open source reimplementation of the Among Us Server
Real_Time_Image_Animation
The Project is real time application in opencv using first order model
Windows-10-Sophia-Script
Script to setup Windows 10 LTSC/1903/1909/2004/2009
annotated_research_papers
This repo contains annotated research papers that I found really good and useful
go-diagrams
Create beautiful system diagrams with Go
crochet
Explorations in reactive UI patterns
led
Modern, lightweight and efficient 2D level editor
duf
Disk Usage/Free Utility
Hazel
Hazel Engine
PayloadsAllTheThings
A list of useful payloads and bypass for Web Application Security and Pentest/CTF
send
Simple, private file sharing from the makers of Firefox
windows
V2ray , Trojan, Trojan-go, NaiveProxy, shadowsocksR install tools for windows V2ray,Trojan,Trojan-go, NaiveProxy, shadowsocksR的一键安装工具windows下用(一键科学上网)
silero-models
Silero Models: pre-trained STT models and benchmarks made embarrassingly simple
vue-next
Repo for Vue 3.0 (currently in RC)
FreeCAD
This is the official source code of FreeCAD, a free and opensource multiplatform 3D parametric modeler. Issues are managed on our own bug tracker at https://www.freecadweb.org/tracker
kb
A minimalist knowledge base manager
Mask_RCNN
Mask R-CNN for object detection and instance segmentation on Keras and TensorFlow
mimikatz
A little tool to play with Windows security
vagas-junior-estagio
Empresas que constantemente oferecem vagas para junior e estagiários
material-shell
A modern desktop interface for Linux. Improve your user experience and get rid of the anarchy of traditional desktop workflows. Designed to simplify navigation and reduce the need to manipulate window
dayjs
⏰ Day.js 2KB immutable date library alternative to Moment.js with the same modern API
ML_course
EPFL Machine Learning Course, Fall 2019
create-react-app
Set up a modern web app by running one command.
Background-Matting
Background Matting: The World is Your Green Screen
Kingfisher
A lightweight, pure-Swift library for downloading and caching images from the web.
istio
Connect, secure, control, and observe services.
linux-command
Linux命令大全搜索工具,内容包含Linux命令手册、详解、学习、搜集。https://git.io/linux
generative_inpainting
DeepFill v1/v2 with Contextual Attention and Gated Convolution, CVPR 2018, and ICCV 2019 Oral
yearn-protocol
Yearn solidity smart contracts
pebble
RocksDB/LevelDB inspired key-value database in Go
jazzit
Laughs at your expense
moment
Parse, validate, manipulate, and display dates in javascript.
n8n
Free and open fair-code licensed node based Workflow Automation Tool. Easily automate tasks across different services.
Hero
Elegant transition library for iOS & tvOS
DAIN
Depth-Aware Video Frame Interpolation (CVPR 2019)
eat_tensorflow2_in_30_days
Tensorflow2.0 ?? is delicious, just eat it! ??
tmpmail
✉️ A temporary email right from your terminal
team-comtress-2
Team Fortress 2, but with a lot of fixes, QoL improvements and performance optimizations!
CVE-2020-1472
PoC for Zerologon - all research credits go to Tom Tervoort of Secura
DefinitelyTyped
The repository for high quality TypeScript type definitions.
rails
Ruby on Rails
stats-illustrations
R & stats illustrations by @allison_horst
pytorch-gans
My implementation of various GAN (generative adversarial networks) architectures like vanilla GAN, cGAN, DCGAN, etc.
data-science-interviews
Data science interview questions and answers
sds1

jupyter-text2code
A proof-of-concept jupyter extension which converts english queries into relevant python code
Notebooks
Learn Python for free using open-source notebooks in Hebrew.
jellyfin
The Free Software Media System
BIGTREETECH-SKR-mini-E3
BIGTREETECH SKR-mini-E3 motherboard is a ultra-quiet, low-power, high-quality 3D printing machine control board. It is launched by the 3D printing team of Shenzhen BIGTREE technology co., LTD. This bo
XiaomiADBFastbootTools
A simple tool for managing Xiaomi devices on desktop using ADB and Fastboot
fastmac
Get a MacOS or Linux shell, for free, in around 2 minutes
pipedream
Serverless integration and compute platform. Free for developers.
DeepVision
在我很多项目中用到的CV算法推理框架应用。
dive
A tool for exploring each layer in a docker image
libra
Libra’s mission is to enable a simple global payment system and financial infrastructure that empowers billions of people.
Kalman-and-Bayesian-Filters-in-Python
Kalman Filter book using Jupyter Notebook. Focuses on building intuition and experience, not formal proofs. Includes Kalman filters,extended Kalman filters, unscented Kalman filters, particle filters,
kinto

CVE-2020-1472
Test tool for CVE-2020-1472
leetcode_company_wise_questions
This is a repository containing the list of company wise questions available on leetcode premium
makani
Makani was a project to develop a commercial-scale airborne wind turbine, culminating in a flight test of the Makani M600 off the coast of Norway. All Makani software has now been open-sourced. This r
Fantasy-Premier-League
Creates a .csv file of all players in the English Player League with their respective team and total fantasy points
996.ICU
Repo for counting stars and contributing. Press F to pay respect to glorious developers.
graal
GraalVM: Run Programs Faster Anywhere ?
understand-nodejs
通过源码分析nodejs原理
tensorboard
TensorFlow's Visualization Toolkit
DeepSpeed
DeepSpeed is a deep learning optimization library that makes distributed training easy, efficient, and effective.
Relativty
An open source VR headset with SteamVR supports for $200
guide-rpc-framework
A custom RPC framework implemented by Netty+Kyro+Zookeeper.(一款基于 Netty+Kyro+Zookeeper 实现的自定义 RPC 框架-附详细实现过程和相关教程。)
UTM
Virtual machines for iOS
v2ray-heroku
用于在 Heroku 上部署 V2Ray Websocket,本项目不宜做为长期使用之对策。
learning
Becoming 1% better at data science everyday
wirehole

minecraft-react

mem-doc
This is a document to help with .NET memory analysis and diagnostics.
HarmonyOS
A curated list of awesome things related to HarmonyOS. 华为鸿蒙操作系统。
radar-covid-backend-dp3t-server
DP^3T Radar COVID fork
eiten
Statistical and Algorithmic Investing Strategies for Everyone
radar-covid-backend-verification-server
Radar COVID Verification Service
radar-covid-ios
Native iOS app using DP^3T iOS sdk to handle Exposure Notification framework from Apple
radar-covid-android
Native Android app using DP^3T Android sdk to handle Exposure Notifications API from Google
react-challenge-amazon-clone

solana
Web-Scale Blockchain for fast, secure, scalable, decentralized apps and marketplaces.
cockroach
CockroachDB - the open source, cloud-native distributed SQL database.
machine-learning-for-trading
Code and resources for Machine Learning for Algorithmic Trading, 2nd edition.
hwp.js
Open source hwp viewer and parser library powered by web technology
awesome-react
A collection of awesome things regarding React ecosystem
connectedhomeip
Project Connected Home over IP is a new Working Group within the Zigbee Alliance. This Working Group plans to develop and promote the adoption of a new connectivity standard to increase compatibility
Yolo-Fastest
⚡ Yolo universal target detection model combined with EfficientNet-lite, the calculation amount is only 230Mflops(0.23Bflops), and the model size is 1.3MB
laravel
A PHP framework for web artisans
onnxruntime
ONNX Runtime: cross-platform, high performance ML inferencing and training accelerator
cim
?cim(cross IM) 适用于开发者的分布式即时通讯系统
ESP32-WiFi-Hash-Monster
WiFi Hash Purple Monster, store EAPOL & PMKID packets in an SD CARD using a M5STACK / ESP32 device
react-portfolio

Algorithms
A collection of algorithms and data structures
frp
A fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet.
funNLP
中英文敏感词、语言检测、中外手机/电话归属地/运营商查询、名字推断性别、手机号抽取、身份证抽取、邮箱抽取、中日文人名库、中文缩写库、拆字词典、词汇情感值、停用词、反动词表、暴恐词表、繁简体转换、英文模拟中文发音、汪峰歌词生成器、职业名称词库、同义词库、反义词库、否定词库、汽车品牌词库、汽车零件词库、连续英文切割、各种中文词向量、公司名字大全、古诗词库、IT词库、财经词库、成语词库、地名词库、历史名
GRAT2
We developed GRAT2 Command & Control (C2) project for learning purpose.
DescomplicandoKubernetes

aes-finder
Utility to find AES keys in running processes
mml-book.github.io
Companion webpage to the book "Mathematics For Machine Learning"
ultimate-python
Ultimate Python study guide for newcomers and professionals alike. ? ? ?
sushiswap-frontend

pytorch-lightning
The lightweight PyTorch wrapper for high-performance AI research. Scale your models, not the boilerplate.
awesome-flutter
An awesome list that curates the best Flutter libraries, tools, tutorials, articles and more.
Interview_Question_for_Beginner
? ? Technical-Interview guidelines written for those who started studying programming. I wish you all the best. ?
free

talk
A group video call for the web. No signups. No downloads.
bitcoin
Bitcoin Core integration/staging tree
eleventy-high-performance-blog
A high performance blog template for the 11ty static site generator.
awesome-project-ideas
Curated list of Machine Learning, NLP, Vision, Recommender Systems Project Ideas
ghcide
A library for building Haskell IDE tooling
moon
? The minimal & fast library for functional user interfaces
jdk
JDK main-line development
Tasmota
Alternative firmware for ESP8266 with easy configuration using webUI, OTA updates, automation using timers or rules, expandability and entirely local control over MQTT, HTTP, Serial or KNX. Full docum
Server
PanDownload的个人维护版本
a32nx
The A32NX Project is a community driven open source project to create a free Airbus A320neo in Microsoft Flight Simulator that is as close to reality as possible. It aims to enhance the default A320ne
keras
Deep Learning for humans
Red-Teaming-Toolkit
A collection of open source and commercial tools that aid in red team operations.
data-engineer-roadmap
Roadmap to becoming a data engineer in 2020
hivemind
Decentralized deep learning framework in pytorch. Built to train models on thousands of volunteers across the world.
scipio
Scipio is a thread-per-core framework that aims to make the task of writing highly parallel asynchronous application in a thread-per-core architecture easier for rustaceans
hoppscotch
? A free, fast and beautiful API request builder used by 75k+ developers. https://hoppscotch.io
Wav2Lip
This repository contains the codes of "A Lip Sync Expert Is All You Need for Speech to Lip Generation In the Wild", published at ACM Multimedia 2020.
KingOfBugBountyTips

autoscraper
A Smart, Automatic, Fast and Lightweight Web Scraper for Python
100-nlp-papers
100 Must-Read NLP Papers
croc
Easily and securely send things from one computer to another ? ?
spark-nlp
State of the Art Natural Language Processing
display-switch
Turn a $30 USB switch into a full-featured multi-monitor KVM switch
surpriver
Find big moving stocks before they move using machine learning and anomaly detection
flink-learning
flink learning blog. http://www.flink-learning.com 含 Flink 入门、概念、原理、实战、性能调优、源码解析等内容。涉及 Flink Connector、Metrics、Library、DataStream API、Table API & SQL 等内容的学习案例,还有 Flink 落地应用的大型项目案例(PVUV、日志存储、百亿数据实时去重、监
deeplearning-models
A collection of various deep learning architectures, models, and tips
fes.js
Fes.js 是一个管理台应用解决方案,提供初始项目、开发调试、编译打包的命令行工具,内置布局、权限、数据字典、状态管理、Api等多个模块,文件目录结构即路由,用户只需要编写页面内容。基于Vue.js,内置管理台常用能力,让用户写的更少,更简单。经过多个项目中打磨,趋于稳定。
stitches
The modern styling library. Near-zero runtime, server-side rendering, multi-variant support, and best-in-class developer experience.
18S191
Course 18.S191 at MIT, fall 2020 - Introduction to computational thinking with Julia
grafana
The tool for beautiful monitoring and metric analytics & dashboards for Graphite, InfluxDB & Prometheus & More
fortify

jetstream

scikit-learn-tips
?⚡ Daily scikit-learn tips
12306
12306智能刷票,订票
desafio-6-2020

30-seconds-of-code
Short JavaScript code snippets for all your development needs
gdal
GDAL is an open source X/MIT licensed translator library for raster and vector geospatial data formats.
toBeTopJavaer
To Be Top Javaer - Java工程师成神之路
companies-sponsoring-visas
A list of companies that sponsor employees from other countries.
howtheytest
A collection of public resources about how software companies test their software
bicep

htop
htop - an interactive process viewer
portainer
Making Docker management easy.
gorm
The fantastic ORM library for Golang, aims to be developer friendly
SuperPower
Here you should find the best power supplies for your low-power projects
CompEcon2020
Computational Economics Course 2020 by Kenneth Judd
vimac
Vimium for macOS.
Windows10Debloater
Script to remove Windows 10 bloatware.
HowToHunt
Some Tutorials and Things to Do while Hunting That Vulnerability.
Hack-Tools
The all-in-one Red Team extension for Web Pentester ?
KingOfBugBountyTips

Showkase
? Showkase is an annotation-processor based Android library that helps you organize, discover, search and visualize Jetpack Compose UI elements
webrtc-for-the-curious
WebRTC for the Curious: Go beyond the APIs
matplotplusplus
Matplot++: A C++ Graphics Library for Data Visualization ??
Flutter-Course-Resources
Learn to Code While Building Apps - The Complete Flutter Development Bootcamp
flutter-development-roadmap
Flutter App Developer Roadmap - A complete roadmap to learn Flutter App Development. I tried to learn flutter using this roadmap. If you want to add something please contribute to the project. Happy L
objax

sushiswap
? SushiSwap smart contracts
Cloudreve
?支持多家云存储的云盘系统 (A project helps you build your own cloud in minutes)
learn-python
? Playground and cheatsheet for learning Python. Collection of Python scripts that are split by topics and contain code examples with explanations.
Python-programming-exercises
100+ Python challenging programming exercises
learn-python3
Jupyter notebooks for teaching/learning Python 3
vscode-debug-visualizer
An extension for VS Code that visualizes data during debugging.
rapier
2D and 3D physics engines focused on performances.
project-guidelines
A set of best practices for JavaScript projects
d3
Bring data to life with SVG, Canvas and HTML. ???
OpenBot
OpenBot leverages smartphones as brains for low-cost robots. We have designed a small electric vehicle that costs about $50 and serves as a robot body. Our software stack for Android smartphones suppo
speakeasy
Windows kernel and user mode emulation.
Learn-Vim
A book for learning the Vim editor
maratona-fullcycle-4

arwes
Futuristic Sci-Fi and Cyberpunk Graphical User Interface Framework for Web Apps
gitignore
A collection of useful .gitignore templates
black
The uncompromising Python code formatter
airflow
Apache Airflow - A platform to programmatically author, schedule, and monitor workflows
shift-ctrl-f
? Search the information available on a webpage using natural language instead of an exact string match.
traefik
The Cloud Native Edge Router
TecoGAN
This repo will contain source code and materials for the TecoGAN project, i.e. code for a TEmporally COherent GAN
present
A terminal-based presentation tool with colors and effects.
gitpod
Gitpod is an open-source Kubernetes application providing prebuilt, collaborative development environments in your browser - powered by VS Code.
compose-samples

react-native-navigation
A complete native navigation solution for React Native
kubernetes-examples
Minimal self-contained examples of standard Kubernetes features and patterns in YAML
vscode
Visual Studio Code
cpp-httplib
A C++ header-only HTTP/HTTPS server and client library
AWS-SAA-C02-Course
Personal notes for SAA-C02 test from: https://learn.cantrill.io
clean-architecture-swiftui
A demo project showcasing the production setup of the SwiftUI app with Clean Architecture
Gooey
Turn (almost) any Python command line program into a full GUI application with one line
baiduwp-php
PanDownload网页复刻版
latexify_py
Generates LaTeX math description from Python functions.
open-source-cs-python

RAFT

volt-bootstrap-5-dashboard
⚡️ Volt Bootstrap 5 Admin Dashboard Template with vanilla Javascript
itlwm
Intel Wi-Fi Drivers
packer
Packer is a tool for creating identical machine images for multiple platforms from a single source configuration.
open-source-cs
Video discussing this curriculum:
nsfw-filter
A Google Chrome / Firefox extension that blocks NSFW images from the web pages that you load using TensorFlow JS.
sudoku-solver
Smart solution to solve sudoku in VR
desafio-4-2020

msfs-a320neo

mit-15-003-data-science-tools
Study guides for MIT's 15.003 Data Science Tools
CascadeTabNet
This repository contains the code and implementation details of the CascadeTabNet paper "CascadeTabNet: An approach for end to end table detection and structure recognition from image-based documents"
certified-kubernetes-administrator-course
Certified Kubernetes Administrator - CKA Course
everyones-guide-for-starting-up-on-wechat-network
微信互联网平民创业
manim
Animation engine for explanatory math videos
CS-Notes
我的自学笔记,在学习shell和MLSys,整理C++、算法、操作系统,后续学习分布式系统,终身更新。
egua
? Linguagem de programação simples e moderna em português
talent-plan
open source training courses about distributed database and distributed systemes
godot
Godot Engine – Multi-platform 2D and 3D game engine
desafio-3-2020

optuna
A hyperparameter optimization framework
Ventoy
A new bootable USB solution.
Alt-F4
Alternative Factorio Friday Fan Facts, also known as Alt-F4
awesome-made-by-brazilians
?? A collection of amazing open source projects built by brazilian developers
zig
General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
cxx
Safe interop between Rust and C++
lireddit

chakra-ui
⚡️ Simple, Modular & Accessible UI Components for your React Applications
VancedManager
Vanced Installer
react-native-video
A
NYPD-Misconduct-Complaint-Database
This database is a record of NYPD misconduct complaints made by the public to the Civilian Complaint Review Board (CCRB).
awesome-django
A curated list of awesome things related to Django
Front-End-Checklist
? The perfect Front-End Checklist for modern websites and meticulous developers
fet.sh
a fetch written in posix shell without any external commands (linux only)
baiduwp
PanDownload Web, built with CloudFlare Workers
machine-learning-interview
Minimum Viable Study Plan for Machine Learning Interviews from FAAG, Snapchat, LinkedIn.
RSSHub
? Everything is RSSible
metamask-extension
? ? The MetaMask browser extension enables browsing Ethereum blockchain enabled websites
amplify-flutter
Amplify Framework provides a declarative and easy-to-use interface across different categories of cloud operations.
ent
An entity framework for Go
pytorch
Tensors and Dynamic neural networks in Python with strong GPU acceleration
element3
(WIP)fork from ElemeFE/element ,A Vue.js 3.0 UI Toolkit for Web
posthog
? PostHog is developer-friendly, open-source product analytics.
awesome-hpp
A curated list of awesome header-only C++ libraries
fabric
Hyperledger Fabric is an enterprise-grade permissioned distributed ledger framework for developing solutions and applications. Its modular and versatile design satisfies a broad range of industry use
insight
Repository for Project Insight: NLP as a Service
omatsuri
Browser application with 9 open source frontend focused tools
InfoSpider
INFO-SPIDER 是一个集众多数据源于一身的爬虫工具箱?,旨在安全快捷的帮助用户拿回自己的数据,工具代码开源,流程透明。支持数据源包括GitHub、QQ邮箱、网易邮箱、阿里邮箱、新浪邮箱、Hotmail邮箱、Outlook邮箱、京东、淘宝、支付宝、中国移动、中国联通、中国电信、知乎、哔哩哔哩、网易云音乐、QQ好友、QQ群、生成朋友圈相册、浏览器浏览历史、12306、博客园、CSDN博客、开源
element-plus
A Vue.js 3.0 UI Toolkit for Web
autoscaler
Autoscaling components for Kubernetes
magento2
All Submissions you make to Magento Inc. ("Magento") through GitHub are subject to the following terms and conditions: (1) You grant Magento a perpetual, worldwide, non-exclusive, no charge, royalty f
ts-migrate
A tool to help migrate JavaScript code quickly and conveniently to TypeScript
ar-cutpaste
Cut and paste your surroundings using AR
chinese-programmer-wrong-pronunciation
中国程序员容易发音错误的单词
labs_campaigns

AdGuardHome
Network-wide ads & trackers blocking DNS server
COLA
Clean Object-oriented & Layered Architecture
Godzilla
哥斯拉
diagrams
? Diagram as Code for prototyping cloud system architectures
PaddleDetection
Object detection and instance segmentation toolkit based on PaddlePaddle.
handcalcs
Python library for converting Python calculations into rendered latex.
mern-course-bootcamp
Complete Free Coding Bootcamp 2020 MERN Stack
handwritten.js
Convert typed text to realistic handwriting!
archivy
Archivy is a self-hosted knowledge repository that allows you to safely preserve useful content that contributes to your knowledge bank.
mall-swarm
mall-swarm是一套微服务商城系统,采用了 Spring Cloud Hoxton & Alibaba、Spring Boot 2.3、Oauth2、MyBatis、Docker、Elasticsearch等核心技术,同时提供了基于Vue的管理后台方便快速搭建系统。mall-swarm在电商业务的基础集成了注册中心、配置中心、监控中心、网关等系统功能。文档齐全,附带全套Spring Clou
umami
Umami is a simple, fast, website analytics alternative to Google Analytics.
nl-covid19-notification-app-android
Android sources for the Dutch Covid19 Notification App
contenidos
Material del curso IIC2233 Programación Avanzada ?
locast2plex
A very simple script to connect locast to Plex's live tv/dvr feature.
h1st
H1st AI solves the critical “cold-start” problem of Industrial AI: encoding human expertise to augment the lack of data, while building a smooth transition toward a machine-learning future. This probl
minGPT
A minimal PyTorch re-implementation of the OpenAI GPT (Generative Pretrained Transformer) training
Catch2
A modern, C++-native, header-only, test framework for unit-tests, TDD and BDD - using C++11, C++14, C++17 and later (or C++03 on the Catch1.x branch)
libra
Ergonomic machine learning.
annie
? Fast, simple and clean video downloader
spotMicro
Spot Micro Quadripeg Project
LeetCode-Go
✅ Solutions to LeetCode by Go, 100% test coverage, runtime beats 100% / LeetCode 题解
bootcamp-gostack-desafios
Repositório contendo todos os desafios dos módulos do Bootcamp Gostack
NoVmp
A static devirtualizer for VMProtect x64 3.x. powered by VTIL.
fullcalendar
Full-sized drag & drop event calendar
latexify_py
Generates LaTeX math description from Python functions.
vue-nodejs-youtube-clone
This is the frontend (VueJS) of the Youtube clone called VueTube.
youtube-clone-nodejs-api
VueTube is a YouTube clone built with nodejs, expressjs & mongodb. This is the RESTful API repository.
Behinder
“冰蝎”动态二进制加密网站管理客户端
low-level-design-primer

E-commerce-Complete-Flutter-UI

handson-ml
A series of Jupyter notebooks that walk you through the fundamentals of Machine Learning and Deep Learning in python using Scikit-Learn and TensorFlow.
aws-machine-learning-university-accelerated-tab

aws-machine-learning-university-accelerated-cv

mogollar
A MongoDB UI built with Electron
BespokeSynth
Software modular synth
desafio-1-2020

desafio-1-2020

kosmonaut
A web browser engine for the space age ?
aws-machine-learning-university-accelerated-nlp

fastbook
Draft of the fastai book
Hierarchical-Localization
Visual localization made easy
TypeScript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
Penetration_Testing_POC
渗透测试有关的POC、EXP、脚本、提权、小工具等,欢迎补充、完善---About penetration-testing python-script poc getshell csrf xss cms php-getshell domainmod-xss penetration-testing-poc csrf-webshell cobub-razor cve rce sql sql-poc p
God-Of-BigData
大数据面试题,大数据成神之路开启...Flink/Spark/Hadoop/Hbase/Hive...
OSCPRepo
A list of commands, scripts, resources, and more that I have gathered and attempted to consolidate for use as OSCP (and more) study material. Commands in 'Usefulcommands' Keepnote. Bookmarks and readi
drogon
Drogon: A C++14/17 based HTTP web application framework running on Linux/macOS/Unix/Windows
papercups
Open-source live customer chat
jupyter-book
Build interactive, publication-quality documents from Jupyter Notebooks
awesome-java
Collection of awesome Java project on Github(Github 上非常棒的 Java 开源项目集合).
espflix
A free video streaming service that runs on a ESP32
servo
The Servo Browser Engine
halfmoon
Front-end framework with a built-in dark mode, designed for rapidly building beautiful dashboards and product pages.
eventnative
EventNative is an open-source data collection framework
go-github
Go library for accessing the GitHub API
yam-protocol
A stablizing reserve currency protocol
mmdetection3d
OpenMMLab's next-generation platform for general 3D object detection.
sherlock
? Hunt down social media accounts by username across social networks
computervision-recipes
Best Practices, code samples, and documentation for Computer Vision.
clean-code-javascript
? Clean Code concepts adapted for JavaScript
laravel-admin
Build a full-featured administrative interface in ten minutes
OpenJailbreak
GeoSn0w's OpenJailbreak Project, an open-source iOS 11 to iOS 13 Jailbreak project & vault.
azure-quickstart-templates
Azure Quickstart Templates
nodejs.dev
A new Node.js resource built using Gatsby.js with React.js, TypeScript, Emotion, and Remark.
KOOM
KOOM is an OOM killer on mobile platform by Kwai.
bevy
A refreshingly simple data-driven game engine built in Rust
eat_pytorch_in_20_days
Pytorch?? is delicious, just eat it! ??
datasets
? 2,000,000+ Unsplash images made available for research and machine learning
malwoverview
Malwoverview is a first response tool to perform an initial and quick triage in a directory containing malware samples, specific malware sample, suspect URL and domains. Additionally, it allows to dow
streisand
Streisand sets up a new server running your choice of WireGuard, OpenConnect, OpenSSH, OpenVPN, Shadowsocks, sslh, Stunnel, or a Tor bridge. It also generates custom instructions for all of these serv
LeetCode
LeetCode刷题记录
IntelOwl
Intel Owl: analyze files, domains, IPs in multiple ways from a single API at scale
archive-program
The GitHub Archive Program & Arctic Code Vault
rancher
Complete container management platform
Noctilucent
Using TLS 1.3 to evade censors, bypass network defenses, and blend in with the noise
data-science
? Path to a free self-taught education in Data Science!
FigmaToCode
Generate responsive pages and apps on Tailwind, Flutter and SwiftUI.
twitter-clone

my-arsenal-of-aws-security-tools
List of open source tools for AWS security: defensive, offensive, auditing, DFIR, etc.
InvoiceNet
Deep neural network to extract intelligent information from invoice documents.
macOS_Big_Sur_icons_replacements
Replacement icons for popular apps in the style of macOS Big Sur
AnimeGANv2
[Open Source]. The improved version of AnimeGAN.
bluezone-app
Bluezone - Bảo vệ mình, bảo vệ cộng đồng
awesome-sysadmin
A curated list of amazingly awesome open source sysadmin resources inspired by Awesome PHP.
facebook-scripts-dom-manipulation
An open-source project includes many scripts with no Access Token needed for Facebook users by directly manipulating the DOM.
MCinaBox
MCinaBox - A Minecraft Java Edition Launcher on Android
ai-economist
Foundation is a flexible, modular, and composable framework to model socio-economic behaviors and dynamics with both agents and governments. This framework can be used in conjunction with reinforcemen
TikTok-Shares-Botter
Adds TikTok Shares for you.
prefect
The easiest way to automate your data
tuya-convert
A collection of scripts to flash Tuya IoT devices to alternative firmwares
crush
Crush is an attempt to make a command line shell that is also a powerful modern programming language.
pyre-check
Performant type-checking for python.
polkadot
Polkadot Node Implementation
incyber

mesh
Cloud native service mesh for the rest of us.
V2rayU
V2rayU,基于v2ray核心的mac版客户端,用于科学上网,使用swift编写,支持vmess,shadowsocks,socks5等服务协议,支持订阅, 支持二维码,剪贴板导入,手动配置,二维码分享等
TLS-poison

heroicons
A set of free MIT-licensed high-quality SVG icons for UI development.
react-native
A framework for building native apps with React.
gui.cs
Console-based user interface toolkit for .NET applications.
Atlas
Atlas: End-to-End 3D Scene Reconstruction from Posed Images
aws-sdk-go
AWS SDK for the Go programming language.
charts
Curated applications for Kubernetes
pybind11
Seamless operability between C++11 and Python
mediapipe
MediaPipe is the simplest way for researchers and developers to build world-class ML solutions and applications for mobile, edge, cloud and the web.
proffy-discovery
A proposta do projeto é uma aplicação que possa ligar quem deseja aprender, com quer ensinar. É possível encontrar alunos para o que você leciona, ou encontrar o professor para aquela matéria que você
mixer
Add-on for real-time collaboration in Blender.
iOS-DeviceSupport
This repository holds the device support files for the iOS, and I will update it regularly.
simdjson
Parsing gigabytes of JSON per second
amplify-js
A declarative JavaScript library for application development using cloud services.
lottie-ios
An iOS library to natively render After Effects vector animations
Faze4-Robotic-arm
All files for 6 axis robot arm with cycloidal gearboxes .
xiaobaiyang

Javascript
A repository for All algorithms implemented in Javascript (for educational purposes only)
blog-post-workflow
Show your latest blog posts from any sources or StackOverflow activity on your GitHub profile/project readme automatically using the RSS feed
reverse-interview
Questions to ask the company during your interview
expo
An open-source platform for making universal native apps with React. Expo runs on Android, iOS, and the web.
955.WLB
955 不加班的公司名单 - 工作 955,work–life balance (工作与生活的平衡)
A-to-Z-Resources-for-Students
✅ Curated list of resources for college students
TDengine
An open-source big data platform designed and optimized for the Internet of Things (IoT).
django-jazzmin
Jazzy theme for Django
full-stack-fastapi-postgresql
Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more.
Reflection_Summary
算法理论基础知识应知应会
Best-websites-a-programmer-should-visit
? Some useful websites for programmers.
bpytop
Linux/OSX/FreeBSD resource monitor
TelemetrySourcerer
Enumerate and disable common sources of telemetry used by AV/EDR.
instagrabber
InstaGrabber, the open-source Instagram client for Android. Originally by @AwaisKing.
pe_tree

Powershell-Scripts
Helpful list of powershell scripts I have found/created
drawio
Source to app.diagrams.net
analytics
Simple and privacy-friendly alternative to Google Analytics
pycaret
An open source, low-code machine learning library in Python
Ciphey
Automated decryption tool
Data-Science-Interview-Resources
A repository listing out the potential sources which will help you in preparing for a Data Science/Machine Learning interview. New resources added frequently.
ps4-ipv6-uaf

UNSAM_2020c2_Python
Curso de programación en Python - 2do cuatrimestre 2020 - UNSAM
gpu.js
GPU Accelerated JavaScript
how-to-secure-anything
How to systematically secure anything: a repository about security engineering
paperview
A high performance X11 animated wallpaper setter
core
? JAVClub - 让你的大姐姐不再走丢
home-cloud
The "cloud" at home
haoel.github.io

InstaPy
? Instagram Bot - Tool for automated Instagram interactions
bat
A cat(1) clone with wings.
DeOldify
A Deep Learning based project for colorizing and restoring old images (and video!)
educative.io_courses
this is downloadings of all educative.io free student subscription courses as pdf from GitHub student pack
rustlings
? Small exercises to get you used to reading and writing Rust code!
trackerslist
Updated list of public BitTorrent trackers
Statistical-Learning-Method_Code
手写实现李航《统计学习方法》书中全部算法
mobile
React Native client application for COVID Shield on iOS and Android
binary_search
A collection of improved binary search algorithms.
mirai

TapTap
Port of the double tap on back of device feature from Android 11 to any armv8 Android device
complete-javascript-course
Starter files, final projects and FAQ for my Complete JavaScript course
icons
Official open source SVG icon library for Bootstrap.
oneflow
OneFlow is a performance-centered and open-source deep learning framework.
ml-engineer-roadmap
WIP: Roadmap to becoming a machine learning engineer in 2020
hvmi
Hypervisor Memory Introspection Core Library
fhe-toolkit-linux
IBM Fully Homomorphic Encryption Toolkit For Linux
teenyicons
Tiny minimal 1px icons designed to fit in the smallest places.
project-citadel
An open source project management tool with Kanban boards
covid-alert-app
Exposure notification client application / Application client de notification d'exposition
ChromeAppHeroes
?谷粒-Chrome插件英雄榜, 为优秀的Chrome插件写一本中文说明书, 让Chrome插件英雄们造福人类~ ChromePluginHeroes, Write a Chinese manual for the excellent Chrome plugin, let the Chrome plugin heroes benefit the human~ 公众号「0加1」同步更新
SSPanel-Uim
SSPanel V3 魔改再次修改版
UnusualVolumeDetector
Gets the last 5 months of volume history for every ticker, and alerts you when a stock's volume exceeds 10 standard deviations from the mean within the last 3 days
formik
Build forms in React, without the tears ?
learn-cantrill-io-labs
Standard and Advanced Demos for learn.cantrill.io courses
TransCoder
Public release of the TransCoder research project https://arxiv.org/pdf/2006.03511.pdf
bounty-targets-data
This repo contains hourly-updated data dumps of bug bounty platform scopes (like Hackerone/Bugcrowd/Intigriti/etc) that are eligible for reports
CtCI-6th-Edition
Cracking the Coding Interview 6th Ed. Solutions
windows95
?? Windows 95 in Electron. Runs on macOS, Linux, and Windows.
SkyArk
SkyArk helps to discover, assess and secure the most privileged entities in Azure and AWS
interviews
Everything you need to know to get the job.
Android-Analysis
Getting Genymotion & Burpsuite setup for Android Mobile App Analysis
detext
DeText: A Deep Neural Text Understanding Framework for Ranking and Classification Tasks
awesome-java
A curated list of awesome frameworks, libraries and software for the Java programming language.
workflow

tye
Tye is a tool that makes developing, testing, and deploying microservices and distributed applications easier. Project Tye includes a local orchestrator to make developing microservices easier and the
java-design-patterns
Design patterns implemented in Java
java8-tutorial
Modern Java - A Guide to Java 8
generator-jhipster
JHipster is a development platform to quickly generate, develop, & deploy modern web applications & microservice architectures.
stayaway-app
Official repository for the STAYAWAY COVID mobile application
api-guidelines
Microsoft REST API Guidelines
win10script
This is the Ultimate Windows 10 Script from a creation from multiple debloat scripts and gists from github.
tutorials
Just Announced - "Learn Spring Security OAuth":
Otto
Otto makes machine learning an intuitive, natural language experience.? Facebook AI Challenge winner
first-order-model
This repository contains the source code for the paper First Order Motion Model for Image Animation
laravel-best-practices
Laravel best practices
hiring-without-whiteboards
⭐️ Companies that don't have a broken hiring process
PyTorch_YOLOv4
PyTorch implementation of YOLOv4
macintosh.js
A virtual Apple Macintosh with System 8, running in Electron. I'm sorry.
QuickCut
Your most handy video processing software
Super-mario-bros-PPO-pytorch
Proximal Policy Optimization (PPO) algorithm for Super Mario Bros
arrow
Apache Arrow is a cross-language development platform for in-memory data. It specifies a standardized language-independent columnar memory format for flat and hierarchical data, organized for efficien
swift
The Swift Programming Language
flutter
Flutter makes it easy and fast to build beautiful apps for mobile and beyond.
pikvm
Open and cheap DIY IP-KVM based on Raspberry Pi
ILSpy
.NET Decompiler with support for PDB generation, ReadyToRun, Metadata (&more) - cross-platform!
aluraflix
⚛️ Projeto feito durante a Imersão React da Alura
starship
☄?️ The minimal, blazing-fast, and infinitely customizable prompt for any shell!
leonsans
Leon Sans is a geometric sans-serif typeface made with code in 2019 by Jongmin Kim.
MCVmComputers
Order computer parts from a satellite orbiting around your minecraft world and build actual working computers with them!

react-query

JavaScript LINK
⚛️ Hooks for fetching, caching and updating asynchronous data in React

React Query Header

Hooks for fetching, caching and updating asynchronous data in React

#TanStack

semantic-release

Join the discussion on Github

Enjoy this library? Try them all! React Table, React Form, React Charts

Quick Features

Core Issues and Solution ## The Challenge Tools for managing "global state" are plentiful these days, but most of these tools: - Mistake **server cache state** for **global state** - Force you to manage async data in a synchronous way - Duplicate unnecessary network operations - Use naive or over-engineered caching strategies - Are too basic to handle large-scale apps or - Are too complex or built for highly-opinionated systems like Redux, GraphQL, [insert proprietary tools], etc. - Do not provide tools for server mutations - Either do not provide easy access to the cache or do, but expose overpowered foot-gun APIs to the developer ## The Solution React Query exports a set of hooks that address these issues. Out of the box, React Query: - Separates your **server cache state** from your **global state** - Provides async aware APIs for reading and updating server state/cache - Dedupes both async and sync requests to async resources - Automatically caches data, invalidates and refetches stale data, and manages garbage collection of unused data - Scales easily as your application grows - Is based solely on Promises, making it highly unopinionated and interoperable with any data fetching strategy including REST, GraphQL and other transactional APIs - Provides an integrated promise-based mutation API - Opt-in Manual or Advance cache management Inspiration & Hat-Tipping
A big thanks to both [Draqula](https://github.com/vadimdemedes/draqula) for inspiring a lot of React Query's original API and documentation and also [Vercel's SWR](https://github.com/zeit/swr) and its creators for inspiring even further customizations and examples. You all rock! How is this different from Vercel's SWR?
[Vercel's SWR](https://github.com/vercel/swr) is a great library, and is very similar in spirit and implementation to React Query with a few notable differences: - Automatic Cache Garbage Collection - React Query handles automatic cache purging for inactive queries and garbage collection. This can mean a much smaller memory footprint for apps that consume a lot of data or data that is changing often in a single session - `useMutation` - A dedicated hook for handling generic lifecycles around triggering mutations and handling their side-effects in applications. SWR does not ship with anything similar, and you may find yourself reimplementing most if not all of `useMutation`'s functionality in user-land. With this hook, you can extend the lifecycle of your mutations to reliably handle successful refetching strategies, failure rollbacks and error handling. - Prefetching - React Query ships with 1st class prefetching utilities which not only come in handy with non-suspenseful apps but also make fetch-as-you-render patterns possible with React Query. SWR does not come with similar utilities and relies on `` and/or manually fetching and updating the query cache - Query cancellation integration is baked into React Query. You can easily use this to wire up request cancellation in most popular fetching libraries, including but not limited to fetch and axios. - Query Key Generation - React Query uses query key generation, query variables, and implicit query grouping. The query key and variables that are passed to a query are less URL/Query-based by nature and much more flexible. All items supplied to the query key array are used to compute the unique key for a query (using a stable and deterministic sorting/hashing implementation). This means you can spend less time thinking about precise key matching, but more importantly, allows you to use partial query-key matching when refetching, updating, or removing queries in mass eg. you can refetch every query that starts with a `todos` in its key, regardless of variables, or you can target specific queries with (or without) variables, and even use functional filtering to select queries in most places. This architecture is much more robust and forgiving especially for larger apps.

Videos and Tutorials

Used By

These analytics are made available via the awesome Scarf package analytics library

Examples

Sponsors

This library is being built and maintained by me, @tannerlinsley and I am always in need of more support to keep projects like this afloat. If you would like to get premium support, add your logo or name on this README, or simply just contribute to my open source Sponsorship goal, visit my Github Sponsors page!

Diamond Sponsors

Get Your Logo Here!

Gold Sponsors

Get Your Logo Here!

Silver Sponsors

Bronze Sponsors

Supporters

Fans

Become a Sponsor

Documentation

Installation

$ npm i --save react-query
# or
$ yarn add react-query

React Query uses Scarf to collect anonymized installation analytics. These analytics help support the maintainers of this library. However, if you'd like to opt out, you can do so by setting scarfSettings.enabled = false in your project's package.json. Alternatively, you can set the environment variable SCARF_ANALYTICS=false before you install.

Defaults to keep in mind

Out of the box, React Query is configured with aggressive but sane defaults. Sometimes these defaults can catch new users off guard or make learning/debugging difficult if they are unknown by the user. Keep them in mind as you continue to learn and use React Query:

Queries

To make a new query, call the useQuery hook with at least:

import { useQuery } from 'react-query'

function App() {
  const info = useQuery('todos', fetchTodoList)
}

The unique key you provide is used internally for refetching, caching, deduping related queries.

The query info returned contains all information about the query and can be easily destructured and used in your component:

function Todos() {
  const { isLoading, isError, data, error } = useQuery('todos', fetchTodoList)

  if (isLoading) {
    return <span>Loading...</span>
  }

  if (isError) {
    return <span>Error: {error.message}</span>
  }

  // also status === 'success', but "else" logic works, too
  return (
    <ul>
      {data.map(todo => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  )
}

If booleans aren't your thing, you can also use the status string to do the same:

function Todos() {
  const { status, data, error } = useQuery('todos', fetchTodoList)

  if (status === 'loading') {
    return <span>Loading...</span>
  }

  if (status === 'error') {
    return <span>Error: {error.message}</span>
  }

  // also status === 'success', but "else" logic works, too
  return (
    <ul>
      {data.map(todo => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  )
}

Query Keys

At its core, React Query manages query caching for you based on query keys. Query keys can be as simple as a string, or as complex as an array or nested object of values. As long as the key is serializable, and unique to the query's data, you can use it!

If you're learning React Query still, we suggest starting with using strings and arrays with strings/numbers, then working your way up to using more complex query keys.

String-Only Query Keys

The simplest form of a key is actually not an array, but an individual string. When a string query key is passed, it is converted to an array internally with the string as the only item in the query key. This format is useful for:

// A list of todos
useQuery('todos', ...) // queryKey === ['todos']

// Something else, whatever!
useQuery('somethingSpecial', ...) // queryKey === ['somethingSpecial']

Array Keys

When a query needs more information to uniquely describe its data, you can use an array with a string and any number of serializable objects to describe it. This is useful for:

// An individual todo
useQuery(['todo', 5], ...)
// queryKey === ['todo', 5]

// And individual todo in a "preview" format
useQuery(['todo', 5, { preview: true }], ...)
// queryKey === ['todo', 5, { preview: 'true' } }]

// A list of todos that are "done"
useQuery(['todos', { type: 'done' }], ...)
// queryKey === ['todos', { type: 'done' }]

Query Keys are serialized deterministically!

This means that no matter the order of keys in objects, all of the following queries would result in the same final query key of ['todos', { page, status }]:

useQuery(['todos', { status, page }], ...)
useQuery(['todos', { page, status }], ...)
useQuery(['todos', { page, status, other: undefined }], ...)

The following query keys, however, are not equal. Array item order matters!

useQuery(['todos', status, page], ...)
useQuery(['todos', page, status], ...)
useQuery(['todos', undefined, page, status], ...)

Query Key Variables

To use external props, state, or variables in a query function, it's easiest to pass them as items in your array query keys! All query keys get passed through to your query function as parameters in the order they appear in the array key:

function Todos({ completed }) {
  const queryInfo = useQuery(['todos', { status, page }], fetchTodoList)
}

// Access the key, status and page variables in your query function!
function fetchTodoList(key, { status, page }) {
  return new Promise()
  // ...
}

If you send through more items in your query key, they will also be available in your query function:

function Todo({ todoId, preview }) {
  const queryInfo = useQuery(['todo', todoId, { preview }], fetchTodoById)
}

// Access status and page in your query function!
function fetchTodoById(key, todoId, { preview }) {
  return new Promise()
  // ...
}

Whenever a query's key changes, the query will automatically update. In the following example, a new query is created whenever todoId changes:

function Todo({ todoId }) {
  const queryInfo = useQuery(['todo', todoId], fetchTodo)
}

Using a Query Object instead of parameters

Anywhere the [queryKey, queryFn, config] signature is supported throughout React Query's API, you can also use an object to express the same configuration:

import { useQuery } from 'react-query'

useQuery({
  queryKey: ['todo', 7],
  queryFn: fetchTodos,
  config: {},
})

Parallel Queries

React Query is built to require no extra effort for making parallel queries. You don't need to do anything special! Just use React Query's hooks and handle all of the loading states and you're good to go!

Dependent Queries

Dependent (or serial) queries are queries that depend on previous ones to finish before they can execute. To do this, use the enabled option to tell a query when it is ready to turn on:

// Get the user
const { data: user } = useQuery(['user', email], getUserByEmail)

// Then get the user's projects
const { isIdle, data: projects } = useQuery(
  ['projects', user.id],
  getProjectsByUser,
  {
    // `user` would be `null` at first (falsy),
    // so the query will not execute until the user exists
    enabled: user,
  }
)

// isIdle will be `true` until `enabled` is true and the query begins to fetch. It will then go to the `isLoading` stage and hopefully the `isSuccess` stage :)

Caching & Invalidation

React Query caching is automatic out of the box. It uses a stale-while-revalidate in-memory caching strategy (popularized by HTTP RFC 5861) and a very robust query deduping strategy to always ensure a query's data is always readily available, only cached when it's needed, even if that query is used multiple times across your application and updated in the background when possible.

At a glance:

A more detailed example of the caching lifecycle Let's assume we are using the default `cacheTime` of **5 minutes** and the default `staleTime` of `0`. - A new instance of `useQuery('todos', fetchTodos)` mounts. - Since no other queries have been made with this query + variable combination, this query will show a hard loading state and make a network request to fetch the data. - It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. - A stale invalidation is scheduled using the `staleTime` option as a delay (defaults to `0`, or immediately). - A second instance of `useQuery('todos', fetchTodos)` mounts elsewhere. - Because this exact data exist in the cache from the first instance of this query, that data is immediately returned from the cache. - Both instances of the `useQuery('todos', fetchTodos)` query are unmounted and no longer in use. - Since there are no more active instances to this query, a cache timeout is set using `cacheTime` to delete and garbage collect the query (defaults to **5 minutes**). - No more instances of `useQuery('todos', fetchTodos)` appear within **5 minutes**. - This query and its data are deleted and garbage collected.

Paginated Queries with usePaginatedQuery

Rendering paginated data is a very common UI pattern to avoid overloading bandwidth or even your UI. React Query exposes a usePaginatedQuery that is very similar to useQuery that helps with this very scenario.

Consider the following example where we would ideally want to increment a pageIndex (or cursor) for a query. If we were to use useQuery, it would technically work fine, but the UI would jump in and out of the success and loading states as different queries are created and destroyed for each page or cursor. By using usePaginatedQuery we get a few new things:

function Todos() {
  const [page, setPage] = React.useState(0)

  const fetchProjects = (key, page = 0) => fetch('/api/projects?page=' + page)

  const {
    isLoading,
    isError,
    error,
    resolvedData,
    latestData,
    isFetching,
  } = usePaginatedQuery(['projects', page], fetchProjects)

  return (
    <div>
      {isLoading ? (
        <div>Loading...</div>
      ) : isError ? (
        <div>Error: {error.message}</div>
      ) : (
        // `resolvedData` will either resolve to the latest page's data
        // or if fetching a new page, the last successful page's data
        <div>
          {resolvedData.projects.map(project => (
            <p key={project.id}>{project.name}</p>
          ))}
        </div>
      )}
      <span>Current Page: {page + 1}</span>
      <button
        onClick={() => setPage(old => Math.max(old - 1, 0))}
        disabled={page === 0}
      >
        Previous Page
      </button>{' '}
      <button
        onClick={() =>
          // Here, we use `latestData` so the Next Page
          // button isn't relying on potentially old data
          setPage(old => (!latestData || !latestData.hasMore ? old : old + 1))
        }
        disabled={!latestData || !latestData.hasMore}
      >
        Next Page
      </button>
      {
        // Since the last page's data potentially sticks around between page requests,
        // we can use `isFetching` to show a background loading
        // indicator since our `status === 'loading'` state won't be triggered
        isFetching ? <span> Loading...</span> : null
      }{' '}
    </div>
  )
}

Load-More & Infinite-Scroll with useInfiniteQuery

Rendering lists that can additively "load more" data onto an existing set of data or "infinite scroll" is also a very common UI pattern. React Query supports a useful version of useQuery called useInfiniteQuery for querying these types of lists.

When using useInfiniteQuery, you'll notice a few things are different:

Example

Let's assume we have an API that returns pages of projects 3 at a time based on a cursor index along with a cursor that can be used to fetch the next group of projects

fetch('/api/projects?cursor=0')
// { data: [...], nextCursor: 3}
fetch('/api/projects?cursor=3')
// { data: [...], nextCursor: 6}
fetch('/api/projects?cursor=6')
// { data: [...], nextCursor: 9}
fetch('/api/projects?cursor=9')
// { data: [...] }

With this information, we can create a "Load More" UI by:

Note: It's very important you do not call fetchMore with arguments unless you want them to override the fetchMoreInfo data returned from the getFetchMore function. eg. Do not do this: <button onClick={fetchMore} /> as this would send the onClick event to the fetchMore function.

import { useInfiniteQuery } from 'react-query'

function Projects() {
  const fetchProjects = (key, cursor = 0) =>
    fetch('/api/projects?cursor=' + cursor)

  const {
    status,
    data,
    isFetching,
    isFetchingMore,
    fetchMore,
    canFetchMore,
  } = useInfiniteQuery('projects', fetchProjects, {
    getFetchMore: (lastGroup, allGroups) => lastGroup.nextCursor,
  })

  return status === 'loading' ? (
    <p>Loading...</p>
  ) : status === 'error' ? (
    <p>Error: {error.message}</p>
  ) : (
    <>
      {data.map((group, i) => (
        <React.Fragment key={i}>
          {group.projects.map(project => (
            <p key={project.id}>{project.name}</p>
          ))}
        </React.Fragment>
      ))}
      <div>
        <button
          onClick={() => fetchMore()}
          disabled={!canFetchMore || isFetchingMore}
        >
          {isFetchingMore
            ? 'Loading more...'
            : canFetchMore
            ? 'Load More'
            : 'Nothing more to load'}
        </button>
      </div>
      <div>{isFetching && !isFetchingMore ? 'Fetching...' : null}</div>
    </>
  )
}

What happens when an infinite query needs to be refetched?

When an infinite query becomes stale and needs to be refetched, each group is fetched sequentially, starting from the first one. This ensures that even if the underlying data is mutated we're not using stale cursors and potentially getting duplicates or skipping records. If an infinite query's results are ever removed from the cache, the pagination restarts at the initial state with only the initial group being requested.

What if I need to pass custom information to my query function?

By default, the info returned from getFetchMore will be supplied to the query function, but in some cases, you may want to override this. You can pass custom variables to the fetchMore function which will override the default info like so:

function Projects() {
  const fetchProjects = (key, cursor = 0) =>
    fetch('/api/projects?cursor=' + cursor)

  const {
    status,
    data,
    isFetching,
    isFetchingMore,
    fetchMore,
    canFetchMore,
  } = useInfiniteQuery('projects', fetchProjects, {
    getFetchMore: (lastGroup, allGroups) => lastGroup.nextCursor,
  })

  // Pass your own custom fetchMoreInfo
  const skipToCursor50 = () => fetchMore(50)
}

What if I want to infinitely load more data in reverse?

Sometimes you may not want to append infintely loaded data, but instead prepend it. If this is case, you can use fetchMore's previous option, eg.

fetchMore(previousPageVariables, { previous: true })

This will ensure the new data is prepended to the data array instead of appended.

Scroll Restoration

Out of the bx, "scroll restoration" for all queries (including paginated and infinite queries) Just Works™️ in React Query. The reason for this is that query results are cached and able to be retrieved synchronously when a query is rendered. As long as your queries are being cached long enough (the default time is 5 minutes)o and have not been garbage collected, scroll restoration will work out of the box all the time.

Disabling or Pausing a Query

If you ever want to disable a query from automatically running, you can use the enabled = false option.

When enabled is false:

function Todos() {
  const {
    isIdle,
    isLoading,
    isError,
    data,
    error,
    refetch,
    isFetching,
  } = useQuery('todos', fetchTodoList, {
    enabled: false,
  })

  return (
    <>
      <button onClick={() => refetch()}>Fetch Todos</button>

      {isIdle ? (
        'Not ready...'
      ) : isLoading ? (
        <span>Loading...</span>
      ) : isError ? (
        <span>Error: {error.message}</span>
      ) : (
        <>
          <ul>
            {data.map(todo => (
              <li key={todo.id}>{todo.title}</li>
            ))}
          </ul>
          <div>{isFetching ? 'Fetching...' : null}</div>
        </>
      )}
    </>
  )
}

Retries

When a useQuery query fails (the query function throws an error), React Query will automatically retry the query if that query's request has not reached the max number of consecutive retries (defaults to 3) or a function is provided to determine if a retry is allowed.

You can configure retries both on a global level and an individual query level.

import { useQuery } from 'react-query'

// Make specific query retry a certain number of times
const queryInfo = useQuery(['todos', 1], fetchTodoListPage, {
  retry: 10, // Will retry failed requests 10 times before displaying an error
})

Retry Delay

By default, retries in React Query do not happen immediately after a request fails. As is standard, a back-off delay is gradually applied to each retry attempt.

The default retryDelay is set to double (starting at 1000ms) with each attempt, but not exceed 30 seconds:

// Configure for all queries
import { ReactQueryConfigProvider } from 'react-query'

const queryConfig = {
  queries: {
    retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
  },
}

function App() {
  return (
    <ReactQueryConfigProvider config={queryConfig}>
      ...
    </ReactQueryConfigProvider>
  )
}

Though it is not recommended, you can obviously override the retryDelay function/integer in both the Provider and individual query options. If set to an integer instead of a function the delay will always be the same amount of time:

const queryInfo = useQuery('todos', fetchTodoList, {
  retryDelay: 1000, // Will always wait 1000ms to retry, regardless of how many retries
})

Prefetching

If you're lucky enough, you may know enough about what your users will do to be able to prefetch the data they need before it's needed! If this is the case, you can use the prefetchQuery function to prefetch the results of a query to be placed into the cache:

import { queryCache } from 'react-query'

const prefetchTodos = async () => {
  const queryData = await queryCache.prefetchQuery('todos', () =>
    fetch('/todos')
  )
  // The results of this query will be cached like a normal query
}

The next time a useQuery instance is used for a prefetched query, it will use the cached data! If no instances of useQuery appear for a prefetched query, it will be deleted and garbage collected after the time specified in cacheTime.

If a prefetched query is rendered after the staleTime for a prefetched query, it will still render, but will be automatically refetched in the background! Cool right?!

Manually Priming a Query

Alternatively, if you already have the data for your query synchronously available, you don't need to prefetch it. You can just use the Query Cache's setQueryData method to directly add or update a query's cached result.

import { queryCache } from 'react-query'

queryCache.setQueryData('todos', todos)

Initial Data

There may be times when you already have the initial data for a query synchronously available in your app. If and when this is the case, you can use the config.initialData option to set the initial data for a query and skip the first round of fetching!

When providing an initialData value that is anything other than undefined:

function Todos() {
  const queryInfo = useQuery('todos', () => fetch('/todos'), {
    initialData: initialTodos,
  })
}

Initial Data Function

If the process for accessing a query's initial data is intensive or just not something you want to perform on every render, you can pass a function as the initialData value. This function will be executed only once when the query is initialized, saving you precious memory and CPU:

function Todos() {
  const queryInfo = useQuery('todos', () => fetch('/todos'), {
    initialData: () => {
      return getExpensiveTodos()
    },
  })
}

Initial Data from Cache

In some circumstances, you may be able to provide the initial data for a query from the cached result of another. A good example of this would be searching the cached data from a todos list query for an individual todo item, then using that as the initial data for your individual todo query:

function Todo({ todoId }) {
  const queryInfo = useQuery(['todo', todoId], () => fetch('/todos'), {
    initialData: () => {
      // Use a todo from the 'todos' query as the initial data for this todo query
      return queryCache.getQueryData('todos')?.find(d => d.id === todoId)
    },
  })
}

Most of the time, this pattern works well, but if the source query you're using to look up the initial data from is old, you may not want to use the data at all and just fetch from the server. To make this decision easier, you can use the queryCache.getQuery method instead to get more information about the source query, including a query.state.updatedAt timestamp you can use to decide if the query is "fresh" enough for your needs:

function Todo({ todoId }) {
  const queryInfo = useQuery(['todo', todoId], () => fetch('/todos'), {
    initialData: () => {
      // Get the query object
      const query = queryCache.getQuery('todos')

      // If the query exists and has data that is no older than 10 seconds...
      if (query && Date.now() - query.state.updatedAt <= 10 * 1000) {
        // return the individual todo
        return query.state.data.find(d => d.id === todoId)
      }

      // Otherwise, return undefined and let it fetch!
    },
  })
}

SSR & Initial Data

When using SSR (server-side-rendering) with React Query there are a few things to note:

const queryInfo = useQuery('todos', fetchTodoList, {
  initialData: [{ id: 0, name: 'Implement SSR!' }],
})

// data === [{ id: 0, name: 'Implement SSR!'}]

Or, alternatively you can just destructure from undefined in your query results:

const { status, data = [{ id: 0, name: 'Implement SSR!' }], error } = useQuery(
  'todos',
  fetchTodoList
)

The query's state will still reflect that it is stale and has not been fetched yet, and once mounted, it will continue as normal and request a fresh copy of the query result.

Suspense Mode

NOTE: Suspense mode for React Query is experimental, same as Suspense for data fetchign itself. These APIs WILL change and should not be used in production unless you lock both your React and React Query versions to patch-level versions that are compatible with each other.

React Query can also be used with React's new Suspense for Data Fetching API's. To enable this mode, you can set either the global or query level config's suspense option to true.

Global configuration:

// Configure for all queries
import { ReactQueryConfigProvider } from 'react-query'

const queryConfig = {
  suspense: true,
}

function App() {
  return (
    <ReactQueryConfigProvider config={queryConfig}>
      ...
    </ReactQueryConfigProvider>
  )
}

Query configuration:

import { useQuery } from 'react-query'

// Enable for an individual query
useQuery(queryKey, queryFn, { suspense: true })

When using suspense mode, status states and error objects are not needed and are then replaced by usage of the React.Suspense component (including the use of the fallback prop and React error boundaries for catching errors). Please see the Suspense Example for more information on how to set up suspense mode.

In addition to queries behaving differently in suspense mode, mutations also behave a bit differently. By default, instead of supplying the error variable when a mutation fails, it will be thrown during the next render of the component it's used in and propagate to the nearest error boundary, similar to query errors. If you wish to disable this, you can set the useErrorBoundary option to false. If you wish that errors are not thrown at all, you can set the throwOnError option to false as well!

Fetch-on-render vs Fetch-as-you-render

Out of the box, React Query in suspense mode works really well as a Fetch-on-render solution with no additional configuration. However, if you want to take it to the next level and implement a Fetch-as-you-render model, we recommend implementing Prefetching on routing and/or user interactions events to initialize queries before they are needed.

Canceling Query Requests

By default, queries that become inactive before their promises are resolved are simply ignored instead of canceled. Why is this?

But don't worry! If your queries are high-bandwidth or potentially very expensive to download, React Query exposes a generic way to cancel query requests using a cancellation token or other related API. To integrate with this feature, attach a cancel function to the promise returned by your query that implements your request cancellation. When a query becomes out-of-date or inactive, this promise.cancel function will be called (if available):

Using axios:

import { CancelToken } from 'axios'

const query = useQuery('todos', () => {
  // Create a new CancelToken source for this request
  const source = CancelToken.source()

  const promise = axios.get('/todos', {
    // Pass the source token to your request
    cancelToken: source.token,
  })

  // Cancel the request if React Query calls the `promise.cancel` method
  promise.cancel = () => {
    source.cancel('Query was cancelled by React Query')
  }

  return promise
})

Using fetch:

const query = useQuery('todos', () => {
  // Create a new AbortController instance for this request
  const controller = new AbortController()
  // Get the abortController's signal
  const signal = controller.signal

  const promise = fetch('/todos', {
    method: 'get',
    // Pass the signal to your request
    signal,
  })

  // Cancel the request if React Query calls the `promise.cancel` method
  promise.cancel = controller.abort

  return promise
})

Mutations

Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a useMutation hook.

Basic Mutations

Assuming the server implements a ping mutation, that returns "pong" string, here's an example of the most basic mutation:

const PingPong = () => {
  const [mutate, { status, data, error }] = useMutation(pingMutation)

  const onPing = async () => {
    try {
      const data = await mutate()
      console.log(data)
      // { ping: 'pong' }
    } catch {
      // Uh oh, something went wrong
    }
  }
  return <button onClick={onPing}>Ping</button>
}

Just as with useQuery you can also use booleans if you'd like:

const [
  mutate,
  { isIdle, isLoading, isError, isSuccess, data, error },
] = useMutation(pingMutation)

Mutations without variables are not that useful, so let's add some variables to closer match reality.

Mutation Variables

To pass variables to your mutate function, call mutate with an object.

// Notice how the fetcher function receives an object containing
// all possible variables
const createTodo = ({ title }) => {
  /* trigger an http request */
}

const CreateTodo = () => {
  const [title, setTitle] = useState('')
  const [mutate] = useMutation(createTodo)

  const onCreateTodo = async e => {
    // Prevent the form from refreshing the page
    e.preventDefault()

    try {
      await mutate({ title })
      // Todo was successfully created
    } catch (error) {
      // Uh oh, something went wrong
    }
  }

  return (
    <form onSubmit={onCreateTodo}>
      <input
        type="text"
        value={title}
        onChange={e => setTitle(e.target.value)}
      />
      <br />
      <button type="submit">Create Todo</button>
    </form>
  )
}

Even with just variables, mutations aren't all that special, but when used with the onSuccess option, the Query Cache's invalidateQueries method and the Query Cache's setQueryData method, mutations become a very powerful tool.

Note that since version 1.1.0, the mutate function is no longer called synchronously so you cannot use it in an event callback. If you need to access the event in onSubmit you need to wrap mutate in another function. This is due to React event pooling.

// This will not work
const CreateTodo = () => {
  const [mutate] = useMutation(event => {
    event.preventDefault()
    fetch('/api', new FormData(event.target))
  })

  return <form onSubmit={mutate}>...</form>
}

// This will work
const CreateTodo = () => {
  const [mutate] = useMutation(formData => {
    fetch('/api', formData)
  })
  const onSubmit = event => {
    event.preventDefault()
    mutate(new FormData(event.target))
  }

  return <form onSubmit={onSubmit}>...</form>
}

Invalidating and Refetching Queries

Waiting for queries to become stale before they are fetched again doesn't always work, especially when you know for a fact that a query needs to get refetched. For that purpose, the queryCache has an invalidateQueries method that lets you manually mark queries as stale and potentially refetch them too!

import { queryCache } from 'react-query'

queryCache.invalidateQueries('todos')

Note: Where other libraries that use normalized caches would attempt to update local queries with the new data imperatively, React Query gives you the tools to avoid the manual labor that comes with maintaining normalized caches and instead prescribes invalidation, background-refetching and ultimately atomic updates.

When a query is invalidated with invalidateQueries, two things happen:

Query Matching with invalidateQueries

When using APIs like invalidateQueries and removeQueries (and others that support partial query matching), you can match multiple queries by their prefix, or get really specific and match an exact query.

In this example, we can use the todos prefix to invalidate any queries that start with todos in their query key:

import { queryCache, useQuery } from 'react-query'

queryCache.invalidateQueries('todos')

// Both queries below will be invalidated
const todoListQuery = useQuery('todos', fetchTodoList)
const todoListQuery = useQuery(['todos', { page: 1 }], fetchTodoList)

You can even invalidate queries with specific variables by passing a more specific query key to the invalidateQueries method:

queryCache.invalidateQueries(['todos', { type: 'done' }])

// The query below will be invalidated
const todoListQuery = useQuery(['todos', { type: 'done' }], fetchTodoList)
// However, the following query below will NOT be invalidated
const todoListQuery = useQuery('todos', fetchTodoList)

The invalidateQueries API is very flexible, so even if you want to only invalidate todos queries that don't have any more variables or subkeys, you can pass an exact: true option to the invalidateQueries method:

queryCache.invalidateQueries('todos', { exact: true })

// The query below will be invalidated
const todoListQuery = useQuery(['todos'], fetchTodoList)
// However, the following query below will NOT be invalidated
const todoListQuery = useQuery(['todos', { type: 'done' }], fetchTodoList)

If you find yourself wanting even more granularity, you can pass a predicate function to the invalidateQueries method. This function will receive each query object from the queryCache and allow you to return true or false for whether you want to invalidate that query:

queryCache.invalidateQueries(
  query => query.queryKey[0] === 'todos' && query.queryKey[1]?.version >= 10
)

// The query below will be invalidated
const todoListQuery = useQuery(['todos', { version: 20 }], fetchTodoList)
// The query below will be invalidated
const todoListQuery = useQuery(['todos', { version: 10 }], fetchTodoList)
// However, the following query below will NOT be invalidated
const todoListQuery = useQuery(['todos', { version: 5 }], fetchTodoList)

Using Mutations to Invalidate Queries

Invalidating queries is only half the battle. Knowing when to invalidate them is the other half. Usually when a mutation in your app succeeds, it's VERY likely that there are related queries in your application that need to be invalidated and possibly refetched to account for the new changes from your mutation.

For example, assume we have a mutation to post a new todo:

const [mutate] = useMutation(postTodo)

When a successful postTodo mutation happens, we likely want all todos queries to get invalidated and possibly refetched to show the new todo item. To do this, you can use useMutation's onSuccess options and the queryCache's invalidateQueries function:

import { useMutation, queryCache } from 'react-query'

// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
const [mutate] = useMutation(addTodo, {
  onSuccess: () => {
    queryCache.invalidateQueries('todos')
    queryCache.invalidateQueries('reminders')
  },
})

You can wire up your invalidations to happen using any of the following side-effect callbacks:

const [mutate] = useMutation(addTodo, {
  onError: () => {
    // An error happened!
  },
  onSuccess: () => {
    // Boom baby!
  },
  onSettled: () => {
    // Error or success... doesn't matter!
  },
})

The promise returned by mutate() can be helpful as well for performing more granualar control flow in your app, and if you prefer that that promise only resolves after the onSuccess or onSettled callbacks, you can return a promise in either!:

const [mutate] = useMutation(addTodo, {
  onSuccess: async () => {
    console.log("I'm first!")
  }),
  onSettled: async () => {
    console.log("I'm second!")
  })
})

const run = async () => {
  try {
    await mutate(todo)
    console.log("I'm third!")
  } catch {}
}

You might find that you want to add additional side-effects to some of the useMutation lifecycle at the time of calling mutate. To do that, you can provide any of the same callback options to the mutate function after your mutation variable. Supported option overrides include:

const [mutate] = useMutation(addTodo, {
  onSuccess: (data, mutationVariables) => {
    // I will fire first
  },
  onSettled: (data, error, mutationVariables) => {
    // I will fire first
  },
  onError: (error, mutationVariables) => {
    // I will fire first
  },
})

mutate(todo, {
  onSuccess: (data, mutationVariables) => {
    // I will fire second!
  },
  onSettled: (data, error, mutationVariables) => {
    // I will fire second!
  },
  onError: (error, mutationVariables) => {
    // I will fire second!
  },
  throwOnError: true,
})

Query Updates from Mutations

When dealing with mutations that update objects on the server, it's common for the new object to be automatically returned in the response of the mutation. Instead of refetching any queries for that item and wasting a network call for data we already have, we can take advantage of the object returned by the mutation function and update the existing query with the new data immediately using the Query Cache's setQueryData method:

const [mutate] = useMutation(editTodo, {
  onSuccess: data => queryCache.setQueryData(['todo', { id: 5 }], data),
})

mutate({
  id: 5,
  name: 'Do the laundry',
})

// The query below will be updated with the response from the
// successful mutation
const { status, data, error } = useQuery(['todo', { id: 5 }], fetchTodoByID)

You might want to tight the onSuccess logic into a reusable mutation, for that you can create a custom hook like this:

const useMutateTodo = () => {
  return useMutate(editTodo, {
    // Notice the second argument is the variables object that the `mutate` function receives
    onSuccess: (data, variables) => {
      queryCache.setQueryData(['todo', { id: variables.id }], data)
    },
  })
}

Resetting Mutation State

It's sometimes the case that you need to clear the error or data of a mutation request. To do this, you can use the reset function to handle this:

const CreateTodo = () => {
  const [title, setTitle] = useState('')
  const [mutate, { error, reset }] = useMutation(createTodo)

  const onCreateTodo = async e => {
    e.preventDefault()
    await mutate({ title })
  }

  return (
    <form onSubmit={onCreateTodo}>
      {error && <h5 onClick={() => reset()}>{error}</h5>}
      <input
        type="text"
        value={title}
        onChange={e => setTitle(e.target.value)}
      />
      <br />
      <button type="submit">Create Todo</button>
    </form>
  )
}

Manually or Optimistically Setting Query Data

In rare circumstances, you may want to manually update a query's response with a custom value. To do this, you can again use the Query Cache's setQueryData method:

It's important to understand that when you manually or optimistically update a query's data value, the potential that you display out-of-sync data to your users is very high. It's recommended that you only do this if you plan to refetch the query very soon or perform a mutation to "commit" your manual changes (and also roll back your eager update if the refetch or mutation fails).

// Full replacement
queryCache.setQueryData(['todo', { id: 5 }], newTodo)

// or functional update
queryCache.setQueryData(['todo', { id: 5 }], previous => ({
  ...previous,
  type: 'done',
}))

Optimistic Updates with Automatic Rollback for Failed Mutations

When you optimistically update your state before performing a mutation, there is a non-zero chance that the mutation will fail. In most cases, you can just trigger a refetch for your optimistic queries to revert them to their true server state. In some circumstances though, refetching may not work correctly and the mutation error could represent some type of server issue that won't make it possible to refetch. In this event, you can instead choose to rollback your update.

To do this, useMutation's onMutate handler option allows you to return a value that will later be passed to both onError and onSettled handlers as the last argument. In most cases, it is most useful to pass a rollback function.

Updating a list of todos when adding a new todo

useMutation(updateTodo, {
  // When mutate is called:
  onMutate: newTodo => {
    // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
    queryCache.cancelQueries('todos')

    // Snapshot the previous value
    const previousTodos = queryCache.getQueryData('todos')

    // Optimistically update to the new value
    queryCache.setQueryData('todos', old => [...old, newTodo])

    // Return the snapshotted value
    return () => queryCache.setQueryData('todos', previousTodos)
  },
  // If the mutation fails, use the value returned from onMutate to roll back
  onError: (err, newTodo, rollback) => rollback(),
  // Always refetch after error or success:
  onSettled: () => {
    queryCache.invalidateQueries('todos')
  },
})

Updating a single todo

useMutation(updateTodo, {
  // When mutate is called:
  onMutate: newTodo => {
    // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
    queryCache.cancelQueries(['todos', newTodo.id])

    // Snapshot the previous value
    const previousTodo = queryCache.getQueryData(['todos', newTodo.id], newTodo)

    // Optimistically update to the new value
    queryCache.setQueryData(['todos', newTodo.id], newTodo)

    // Return a rollback function
    return () => queryCache.setQueryData(['todos', newTodo.id], previousTodo)
  },
  // If the mutation fails, use the rollback function we returned above
  onError: (err, newTodo, rollback) => rollback(),
  // Always refetch after error or success:
  onSettled: () => {
    queryCache.invalidateQueries(['todos', newTodo.id])
  },
})

You can also use the onSettled function in place of the separate onError and onSuccess handlers if you wish:

useMutation(updateTodo, {
  // ...
  onSettled: (newTodo, error, variables, rollback) => {
    if (error) {
      rollback()
    }
  },
})

Displaying Background Fetching Loading States

A query's status === 'loading' state is sufficient enough to show the initial hard-loading state for a query, but sometimes you may want to display an additional indicator that a query is refetching in the background. To do this, queries also supply you with an isFetching boolean that you can use to show that it's in a fetching state, regardless of the state of the status variable:

function Todos() {
  const { status, data: todos, error, isFetching } = useQuery(
    'todos',
    fetchTodos
  )

  return status === 'loading' ? (
    <span>Loading...</span>
  ) : status === 'error' ? (
    <span>Error: {error.message}</span>
  ) : (
    <>
      {isFetching ? <div>Refreshing...</div> : null}

      <div>
        {todos.map(todo => (
          <Todo todo={todo} />
        ))}
      </div>
    </>
  )
}

Displaying Global Background Fetching Loading State

In addition to individual query loading states, if you would like to show a global loading indicator when any queries are fetching (including in the background), you can use the useIsFetching hook:

import { useIsFetching } from 'react-query'

function GlobalLoadingIndicator() {
  const isFetching = useIsFetching()

  return isFetching ? (
    <div>Queries are fetching in the background...</div>
  ) : null
}

Window-Focus Refetching

If a user leaves your application and returns to stale data, you may want to trigger an update in the background to update any stale queries. Thankfully, React Query does this automatically for you, but if you choose to disable it, you can use the ReactQueryConfigProvider's refetchOnWindowFocus option to disable it:

const queryConfig = { queries: { refetchOnWindowFocus: false } }

function App() {
  return (
    <ReactQueryConfigProvider config={queryConfig}>
      ...
    </ReactQueryConfigProvider>
  )
}

Custom Window Focus Event

In rare circumstances, you may want to manage your own window focus events that trigger React Query to revalidate. To do this, React Query provides a setFocusHandler function that supplies you the callback that should be fired when the window is focused and allows you to set up your own events. When calling setFocusHandler, the previously set handler is removed (which in most cases will be the default handler) and your new handler is used instead. For example, this is the default handler:

setFocusHandler(handleFocus => {
  // Listen to visibillitychange and focus
  if (typeof window !== 'undefined' && window.addEventListener) {
    window.addEventListener('visibilitychange', handleFocus, false)
    window.addEventListener('focus', handleFocus, false)
  }

  return () => {
    // Be sure to unsubscribe if a new handler is set
    window.removeEventListener('visibilitychange', handleFocus)
    window.removeEventListener('focus', handleFocus)
  }
})

Ignoring Iframe Focus Events

A great use-case for replacing the focus handler is that of iframe events. Iframes present problems with detecting window focus by both double-firing events and also firing false-positive events when focusing or using iframes within your app. If you experience this, you should use an event handler that ignores these events as much as possible. I recommend this one! It can be set up in the following way:

import { setFocusHandler } from 'react-query'
import onWindowFocus from './onWindowFocus' // The gist above

setFocusHandler(onWindowFocus) // Boom!

Custom Query Key Serializers (Super-duper Advanced)

WARNING: This is a very advanced feature. There be dragons here. Do not change the Query Key Serializer unless you know what you are doing and are fine with encountering edge cases in React Query's API

Show Me The Dragons! If you absolutely despise the default query key implementation, then please file an issue in this repo first. If you still believe you need something different, then you can choose to replace the default query key serializer with your own by using the `ReactQueryConfigProvider` hook's `queryKeySerializerFn` option: ```js const queryConfig = { queryKeySerializerFn: queryKey => { // Your custom logic here... // Make sure object keys are sorted and all values are // serializable const queryFnArgs = getQueryArgs(queryKey) // Hash the query key args to get a string const queryHash = hash(queryFnArgs) // Return both the queryHash and normalizedQueryHash as a tuple return [queryHash, queryFnArgs] }, } function App() { return ( ... ) } ``` - `userQueryKey: any` - This is the queryKey passed in `useQuery` and all other public methods and utilities exported by React Query. - It may be a string or an array of serializable values - If a string is passed, it must be wrapped in an array when returned as the `queryFnArgs` - `queryHash: string` - This must be a unique `string` representing the entire query key. - It must be stable and deterministic and should not change if things like the order of variables are changed or shuffled. - `queryFnArgs: Array` - This array will be spread into the query function arguments and should be the same format as the queryKey but be deterministically stable and should not change structure if the variables of the query stay the same, but change order within array position. > An additional `stableStringify` utility is also exported to help with stringifying objects to have sorted keys. ### URL Query Key Serializer Example The example below shows how to build your own serializer for use with URLs and use it with React Query: ```js import { ReactQueryConfigProvider, stableStringify } from 'react-query' function urlQueryKeySerializer(queryKey) { // Deconstruct the url let [url, params = ''] = queryKey.split('?') // Remove trailing slashes from the url to make an ID url = url.replace(/\/{1,}$/, '') // Build the searchQuery object params.split('&').filter(Boolean) // If there are search params, return a different key if (Object.keys(params).length) { let searchQuery = {} params.forEach(param => { const [key, value] = param.split('=') searchQuery[key] = value }) // Use stableStringify to turn searchQuery into a stable string const searchQueryHash = stableStringify(searchQuery) // Get the stable json object for the normalized key searchQuery = JSON.parse(searchQueryHash) return [`${url}_${searchQueryHash}`, [url, searchQuery]] } return [url, [url]] } const queryConfig = { queryKeySerializerFn: urlQueryKeySerializer, } function App() { return ( ... ) } // Heck, you can even make your own custom useQueryHook! function useUrlQuery(url, options) { return useQuery(url, (url, params) => axios .get(url, { params, }) .then(res => res.data) ) } // Use it in your app! function Todos() { const todosQuery = useUrlQuery(`/todos`) } function FilteredTodos({ status = 'pending' }) { const todosQuery = useUrlQuery(`/todos?status=pending`) } function Todo({ id }) { const todoQuery = useUrlQuery(`/todos/${id}`) } refetchQuery('/todos') refetchQuery('/todos?status=pending') refetchQuery('/todos/5') ``` ### Function Query Key Serializer Example The example below shows how to you build your own functional serializer and use it with React Query: ```js import { ReactQueryConfigProvider, stableStringify } from 'react-query' // A map to keep track of our function pointers const functionSerializerMap = new Map() function functionQueryKeySerializer(queryKey) { if (!queryKey) { return [] } let queryFn = queryKey let variables if (Array.isArray(queryKey)) { queryFn = queryKey[0] variables = queryKey[1] } // Get or create an ID for the function pointer const queryGroupId = functionSerializerMap.get(queryFn) || (() => { const id = Date.now() functionSerializerMap.set(queryFn, id) return id })() const variablesIsObject = isObject(variables) const variablesHash = variablesIsObject ? stableStringify(variables) : '' const queryHash = `${queryGroupId}_${variablesHash}` return [queryHash, queryGroupId, variablesHash, variables] } const queryConfig = { queryKeySerializerFn: functionQueryKeySerializer, } function App() { return ( ... ) } // Heck, you can even make your own custom useQueryHook! function useFunctionQuery(functionTuple, options) { const [queryFn, variables] = Array.isArray(functionTuple) ? functionTuple : [functionTuple] return useQuery(functionTuple, queryFn, options) } // Use it in your app! function Todos() { const todosQuery = useFunctionQuery(getTodos) } function FilteredTodos({ status = 'pending' }) { const todosQuery = useFunctionQuery([getTodos, { status }]) } function Todo({ id }) { const todoQuery = useFunctionQuery([getTodo, { id }]) } refetchQuery(getTodos) refetchQuery([getTodos, { type: 'pending' }]) refetchQuery([getTodo, { id: 5 }]) ```

React Query Devtools

React query has dedicated devtools! Visit the React Query Devtools Github Repo for information on how to install and use them!

To see a demo, check out the Sandbox example!

React Query Header

API

useQuery

const {
  status,
  isIdle,
  isLoading,
  isSuccess,
  isError,
  data,
  error,
  isFetching,
  failureCount,
  refetch,
} = useQuery(queryKey, queryFn, {
  suspense,
  queryKeySerializerFn,
  enabled,
  retry,
  retryDelay,
  staleTime,
  cacheTime,
  refetchOnWindowFocus,
  refetchInterval,
  queryFnParamsFilter,
  refetchOnMount,
  isDataEqual,
  onError,
  onSuccess,
  onSettled,
  useErrorBoundary,
})

// or using the object syntax

const queryInfo = useQuery({
  queryKey,
  queryFn,
  config,
})

Options

Returns

usePaginatedQuery

const {
  data = undefined,
  resolvedData,
  latestData,
  ...queryInfo
} = usePaginatedQuery(queryKey, queryFn, options)

Options

The options for usePaginatedQuery are identical to the useQuery hook

Returns

The returned properties for usePaginatedQuery are identical to the useQuery hook, with the addition of the following:

useInfiniteQuery


const queryFn = (...queryKey, fetchMoreVariable) // => Promise

const {
  isFetchingMore,
  fetchMore,
  canFetchMore,
  ...queryInfo
} = useInfiniteQuery(queryKey, queryFn, {
  ...queryOptions,
  getFetchMore: (lastPage, allPages) => fetchMoreVariable
})

Options

The options for usePaginatedQuery are identical to the useQuery hook with the addition of the following:

Returns

The returned properties for usePaginatedQuery are identical to the useQuery hook, with the addition of the following:

useMutation

const [
  mutate,
  { status, isIdle, isLoading, isSuccess, isError, data, error, reset },
] = useMutation(mutationFn, {
  onMutate,
  onSuccess,
  onError,
  onSettled,
  throwOnError,
  useErrorBoundary,
})

const promise = mutate(variables, {
  onSuccess,
  onSettled,
  onError,
  throwOnError,
})

Options

Returns

queryCache

The queryCache instance is the backbone of React Query that manages all of the state, caching, lifecycle and magic of every query. It supports relatively unrestricted, but safe, access to manipulate query's as you need. Its available properties and methods are:

queryCache.prefetchQuery

prefetchQuery is an asynchronous function that can be used to fetch and cache a query response before it is needed or rendered with useQuery and friends.

The difference between using prefetchQuery and setQueryData is that prefetchQuery is async and will ensure that duplicate requests for this query are not created with useQuery instances for the same query are rendered while the data is fetching.

const data = await queryCache.prefetchQuery(queryKey, queryFn)

For convenience in syntax, you can also pass optional query variables to prefetchQuery just like you can useQuery:

const data = await queryCache.prefetchQuery(queryKey, queryFn, config)

To pass options like force or throwOnError, use the fourth options object:

const data = await queryCache.prefetchQuery(queryKey, queryFn, config, {
  force: true,
  throwOnError: true,
})

Options

The options for prefetchQuery are exactly the same as those of useQuery with the exception of the last options object:

Returns

queryCache.getQueryData

getQueryData is a synchronous function that can be used to get an existing query's cached data. If the query does not exist, undefined will be returned.

import { queryCache } from 'react-query'

const data = queryCache.getQueryData(queryKey)

Options

Returns

queryCache.setQueryData

setQueryData is a synchronous function that can be used to immediately update a query's cached data. If the query does not exist, it will be created and immediately be marked as stale. If the query is not utilized by a query hook in the default cacheTime of 5 minutes, the query will be garbage collected.

The difference between using setQueryData and prefetchQuery is that setQueryData is sync and assumes that you already synchronously have the data available. If you need to fetch the data asynchronously, it's suggested that you either refetch the query key or use prefetchQuery to handle the asynchronous fetch.

import { queryCache } from 'react-query'

queryCache.setQueryData(queryKey, updater, config)

Options

Using an updater value

setQueryData(queryKey, newData)

Using an updater function

For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:

setQueryData(queryKey, oldData => newData)

queryCache.invalidateQueries

The invalidateQueries method can be used to invalidate and refetch single or multiple queries in the cache based on their query keys or any other functionally accessible property/state of the query. By default, all matching queries are immediately marked as stale and active queries are refetched in the background. If you don't want active queries to refetch, and simply be marked as stale, you can use the refetchActive: false option.

import { queryCache } from 'react-query'

const queries = queryCache.invalidateQueries(inclusiveQueryKeyOrPredicateFn, {
  exact,
  throwOnError,
  refetchActive,
})

Options

Returns

This function returns a promise that will resolve when all of the queries are done being refetched. By default, it will not throw an error if any of those queries refetches fail, but this can be configured by setting the throwOnError option to true

queryCache.cancelQueries

The cancelQueries method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.

This is most useful when performing optimistic updates since you will likely need to cancel any outgoing query refetches so they don't clobber your optimistic update when they resolve.

import { queryCache } from 'react-query'

const queries = queryCache.cancelQueries(queryKeyOrPredicateFn, {
  exact,
})

Options

Returns

This function does not return anything

queryCache.removeQueries

The removeQueries method can be used to remove queries from the cache based on their query keys or any other functionally accessible property/state of the query.

import { queryCache } from 'react-query'

const queries = queryCache.removeQueries(queryKeyOrPredicateFn, {
  exact,
})

Options

Returns

This function does not return anything

queryCache.getQuery

getQuery is a slightly more advanced synchronous function that can be used to get an existing query object from the cache. This object not only contains all the state for the query, but all of the instances, and underlying guts of the query as well. If the query does not exist, undefined will be returned.

Note: This is not typically needed for most applications, but can come in handy when needing more information about a query in rare scenarios (eg. Looking at the query.state.updatedAt timestamp to decide whether a query is fresh enough to be used as an initial value)

import { queryCache } from 'react-query'

const query = queryCache.getQuery(queryKey)

Options

Returns

queryCache.getQueries

getQueries is even more advanced synchronous function that can be used to get existing query objects from the cache that partially match query key. If queries do not exist, empty array will be returned.

Note: This is not typically needed for most applications, but can come in handy when needing more information about a query in rare scenarios

import { queryCache } from 'react-query'

const queries = queryCache.getQueries(queryKey)

Options

Returns

queryCache.isFetching

This isFetching property is an integer representing how many queries, if any, in the cache are currently fetching (including background-fetching, loading new pages, or loading more infinite query results)

import { queryCache } from 'react-query'

if (queryCache.isFetching) {
  console.log('At least one query is fetching!')
}

React Query also exports a handy useIsFetching hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache.

queryCache.subscribe

The subscribe method can be used to subscribe to the query cache as a whole and be informed of safe/known updates to the cache like query states changing or queries being updated, added or removed

import { queryCache } from 'react-query'

const callback = cache => {}

const unsubscribe = queryCache.subscribe(callback)

Options

Returns

queryCache.clear

The clear method can be used to clear the queryCache entirely and start fresh.

import { queryCache } from 'react-query'

queryCache.clear()

Returns

useQueryCache

The useQueryCache hook returns the current queryCache instance.

import { useQueryCache } from 'react-query'

const queryCache = useQueryCache()

If you are using the ReactQueryCacheProvider to set a custom cache, you cannot simply import { queryCache } any more. This hook will ensure you're getting the correct instance.

useIsFetching

useIsFetching is an optional hook that returns the number of the queries that your application is loading or fetching in the background (useful for app-wide loading indicators).

import { useIsFetching } from 'react-query'

const isFetching = useIsFetching()

Returns

ReactQueryConfigProvider

ReactQueryConfigProvider is an optional provider component and can be used to define defaults for all instances of useQuery within it's sub-tree:

import { ReactQueryConfigProvider } from 'react-query'

const queryConfig = {
  shared: {
    suspense: false,
    queryKeySerializerFn: defaultQueryKeySerializerFn,
  },
  queries: {
    ...shared,
    enabled: true,
    retry: 3,
    retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
    staleTime: 0,
    cacheTime: 5 * 60 * 1000,
    refetchOnWindowFocus: true,
    refetchInterval: false,
    queryFnParamsFilter: identity,
    refetchOnMount: true,
    isDataEqual: deepEqual,
    onError: noop,
    onSuccess: noop,
    onSettled: noop,
    useErrorBoundary: false, // falls back to suspense
  },
  mutations: {
    ...shared,
    throwOnError: false,
    onMutate: noop,
    onError: noop,
    onSuccess: noop,
    onSettled: noop,
    useErrorBoundary: false, // falls back to suspense
  },
}

function App() {
  return (
    <ReactQueryConfigProvider config={queryConfig}>
      ...
    </ReactQueryConfigProvider>
  )
}

Options

ReactQueryCacheProvider

ReactQueryCacheProvider is an optional provider component for explicitly setting the query cache used by React Query. This is useful for creating component-level caches that are not completely global, as well as making truly isolated unit tests.

import { ReactQueryCacheProvider, makeQueryCache } from 'react-query'

const queryCache = makeQueryCache()

function App() {
  return (
    <ReactQueryCacheProvider queryCache={queryCache}>
      ...
    </ReactQueryCacheProvider>
  )
}

Options

setConsole

setConsole is an optional utility function that allows you to replace the console interface used to log errors. By default, the window.console object is used. If no global console object is found in the environment, nothing will be logged.

import { setConsole } from 'react-query'
import { printLog, printWarn, printError } from 'custom-logger'

setConsole({
  log: printLog,
  warn: printWarn,
  error: printError,
})

Options

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Tanner Linsley

? ? ? ? ?

Andrew Cherniavskii

? ?

Thibaut Tiberghien

?

Rohit Garg

?

Avinash

?

This project follows the all-contributors specification. Contributions of any kind welcome!