Install
npm install react-hydrate-query
yarn add react-hydrate-query
External dependencies
react
axios
Usage
Server
import { ServerProvider } from "react-hydrate-query";
<ServerProvider hydrateState={myServerState}>
<App />
</ServerProvider>
Html
<html>
<head>
<script
dangerouslySetInnerHTML={{
__html: `window.HYDRATE_STATE=${JSON.stringify(myServerState)}`
}}
/>
</head>
<body>
<div
id="root"
className="root"
dangerouslySetInnerHTML={{ __html: content }}
/>
{scripts}
</body>
</html>
Client
import { hydrateRoot } from "react-dom/client";
import { ClientProvider } from "react-hydrate-query";
const container = document.getElementById("root");
hydrateRoot(container, <ClientProvider>
<App />
</ClientProvider>);
useHydrateState
//Gets data from ssr
import { useHydrateState } from "react-hydrate-query";
const [state, setState] = useHydrateState({ key: "test" });
- key - window.HYDRATE_STATE object field
useHydrateQuery
//Gets data from ssr, if they are missing executes the request
import { useHydrateQuery } from "react-hydrate-query";
const [state, setState, isLoading] = useHydrateQuery({ key: "test", url: "/api/test", params: {} });
- key - window.HYDRATE_STATE object field
- url - request url (only post available now)
- params - request params
- onError - error handler (Axios Error)