Skip to content

Commit

Permalink
add SSR section to readme
Browse files Browse the repository at this point in the history
  • Loading branch information
polemius committed May 17, 2023
1 parent 14d1f7b commit 050c87f
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,49 @@ const { persistAtom } = recoilPersist({

![Example of persist state in localStorage](example.png)

## Server Side Rendering

If you are using SSR you could see that error:

```
Unhandled Runtime Error
Error: Text content does not match server-rendered HTML.
```

It happens because on server you don't have any storages and react renders component with default value.
However in browser it is rendering with values from storage.
To prevent it we need to introduce hook for render with default value for the first time.

```
const defaultValue = [{ id: 1 }]
export const recoilTest = atom<{ id: number }[]>({
key: "recoilTest",
default: defaultValue,
effects_UNSTABLE: [persistAtom],
});
export function useSSR() {
const [isInitial, setIsInitial] = useState(true);
const [value, setValue] = useRecoilState(recoilTest);
useEffect(() => {
setIsInitial(false);
}, []);
return [isInitial ? defaultValue : value, setValue] as const;
}
export default function Component() {
const [text, setText] = useSSR();
// rest of the code
}
```


## API

### recoilPersist(config)
Expand Down

0 comments on commit 050c87f

Please sign in to comment.