{"library":"react-query-auth","title":"React Query Authentication Hooks","description":"react-query-auth is a specialized library designed to streamline user authentication management within React applications by leveraging `@tanstack/react-query`. It provides a `configureAuth` function that acts as a factory, generating custom hooks (`useUser`, `useLogin`, `useRegister`, `useLogout`) and an `AuthLoader` component. These utilities abstract away the complexities of integrating authentication state with React Query's caching mechanisms, treating user data as server state. The current stable version is `2.4.3`. While no explicit release cadence is stated, the versioning suggests active maintenance and development. Its key differentiator lies in its deep integration with React Query, offering a consistent approach to manage authentication alongside other server-derived data, reducing boilerplate for common authentication flows. It requires users to provide their own API interaction functions for fetching, logging in, registering, and logging out, making it adaptable to any backend or authentication method.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install react-query-auth"],"cli":null},"imports":["import { configureAuth } from 'react-query-auth';","import { AuthLoader } from 'react-query-auth';","const { useUser, useLogin, useRegister, useLogout } = configureAuth({...});"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import React from 'react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { configureAuth, AuthLoader } from 'react-query-auth';\n\nconst queryClient = new QueryClient();\n\n// Mock API functions for demonstration\nconst api = {\n  get: async (url: string) => {\n    if (url === '/me') {\n      // Simulate authenticated user\n      const user = localStorage.getItem('mock-user');\n      return user ? JSON.parse(user) : null;\n    }\n    throw new Error('Not found');\n  },\n  post: async (url: string, data?: any) => {\n    if (url === '/login' && data.email === 'test@example.com' && data.password === 'password') {\n      const user = { id: '123', email: data.email };\n      localStorage.setItem('mock-user', JSON.stringify(user));\n      return user;\n    }\n    if (url === '/register') {\n      const user = { id: '456', email: data.email };\n      localStorage.setItem('mock-user', JSON.stringify(user));\n      return user;\n    }\n    if (url === '/logout') {\n      localStorage.removeItem('mock-user');\n      return null;\n    }\n    throw new Error('API Error');\n  }\n};\n\nconst { useUser, useLogin, useLogout } = configureAuth({\n  userFn: () => api.get('/me'),\n  loginFn: (credentials) => api.post('/login', credentials),\n  registerFn: (credentials) => api.post('/register', credentials),\n  logoutFn: () => api.post('/logout')\n});\n\nfunction UserInfo() {\n  const user = useUser();\n  const logout = useLogout();\n\n  if (user.isLoading) {\n    return <div>Loading user info...</div>;\n  }\n\n  if (user.error) {\n    return <div style={{ color: 'red' }}>Error: {user.error.message}</div>;\n  }\n\n  if (!user.data) {\n    return (\n      <div>\n        <div>Not logged in</div>\n        <button onClick={() => useLogin().mutate({ email: 'test@example.com', password: 'password' })}>Login</button>\n      </div>\n    );\n  }\n\n  return (\n    <div>\n      <div>Logged in as {user.data.email}</div>\n      <button disabled={logout.isLoading} onClick={() => logout.mutate({})}>\n        Log out\n      </button>\n    </div>\n  );\n}\n\nfunction AuthScreen() {\n  const login = useLogin();\n  const register = useRegister();\n\n  const handleLogin = () => login.mutate({ email: 'test@example.com', password: 'password' });\n  const handleRegister = () => register.mutate({ email: 'new@example.com', password: 'password' });\n\n  return (\n    <div>\n      <h2>Authentication</h2>\n      <button onClick={handleLogin}>Login as Test User</button>\n      <button onClick={handleRegister}>Register New User</button>\n      {login.error && <div style={{ color: 'red' }}>Login Error: {login.error.message}</div>}\n      {register.error && <div style={{ color: 'red' }}>Register Error: {register.error.message}</div>}\n    </div>\n  );\n}\n\nfunction App() {\n  return (\n    <QueryClientProvider client={queryClient}>\n      <h1>My Auth App</h1>\n      <AuthLoader\n        renderLoading={() => <div>Initial authentication check...</div>}\n        renderUnauthenticated={() => <AuthScreen />}\n      >\n        <UserInfo />\n      </AuthLoader>\n    </QueryClientProvider>\n  );\n}\n\nexport default App;\n","lang":"typescript","description":"This quickstart demonstrates how to configure `react-query-auth` with mock API functions, use the generated `useUser`, `useLogin`, and `useLogout` hooks, and implement the `AuthLoader` component to manage initial loading and authentication states within a React Query application.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}