npm.io
1.0.1 • Published 6 years ago

stateful-hooks

Licence
MIT
Version
1.0.1
Deps
0
Size
13 kB
Vulns
0
Weekly
0
Stars
6

stateful-hooks

Version Documentation Maintenance License: MIT Twitter: davidmarkclem

Give your react hooks state on the server side

Homepage

Usage

This is a drop-in module that will modifiy React hooks SSR behaviour.

Use as a preloaoder

node -r stateful-hooks my-app.js

Or react in the entry point before requiring react:

require('stateful-hooks')
const React = require('react')

Install

npm install

Run tests

npm test

Stateful Hooks

The following hooks retain state on the server side when stateful-hooks has been applied:

  • useState - persists state across requests
  • useReducer - persists state across requests
  • useMemo - persists memoization across requests
  • useCallback - persists memoization across requests
  • useContext - supplies context state during ssr
  • useRef - returns {current: input} instead of undefined
  • useEffect - can be enabled on a case by case basis by setting useEffect.ssr to true. In SSR mode use effect is called during rendering.

Server-side useEffect

useEffect is a client-side only hook, however we can opt in to making the useEffect call into a server-side hook by setting useEffect.ssr = true right before it is called:

import { useEffect } from 'react'
const MyComponent = () => {
  const [ state, update ] = useState(0)
  useEffect.ssr = true
  useEffect(() => {
    update(1) // this will be called server side
  })
  useEffect(() => {
    update(2) // this will NOT be called server side
  })
}

Avoiding server state

In the event that server state is unwanted in a particular context, ensure the update function is called within useEffect (without setting useEffect.ssr to true) so that it's client side only.

Author

David Mark Clements

Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page.

Show your support

Give a ️ if this project helped you!

License

Copyright 2020 David Mark Clements.
This project is MIT licensed.


This README was generated with by readme-md-generator

Keywords