React Hooks - state and lifecycle methods without a class (React 16.7.0-alpha)

i like it, but i see a potential concurrency problem on SSR with meteor, see https://github.com/meteor/meteor/issues/10279

how i understand the hooks is, that they store some caller–>hook dependency. So on every render call of a component, they set some global state to the current calling component, so that every hook/effect call knows which component it belongs to.

this work fine, with normal javascript environments, as long as you don’t use asynchronous callbacks (like setTimeout)

on meteor servers, however, you have fibers. and fibers can stop/yield execution of code on certain points (like on a Collection.findOne() call).

This could potentioally break hooks/effects in a similar way like it breaks React.createContext (see link above) when doing server side rendering.

its probably not a big problem with more recent apps that use apollo, where the whole <App /> has no fiber-yields, but it can be, if you use pub/sub.

I don’t know the exact implementation, so this is only guessing. Maybe there will be also a fix involving Fiber.current like i did for the context api (https://github.com/panter/meteor-fiber-save-react-context)

1 Like

@macrozone

At this stage of the alpha hooks are not supported on the server yet, so that’s hard to say for sure.

For the specific case of “provide reactive Meteor data to React components through a hook”, though, I’d say it’s likely not going to be a problem : the current implementation of the withTracker(reactiveFun) HOC basically just does if (Meteor.isServer) return reactiveFun(props), and a useTrackerHook(reactiveFun) will probably do the same (that’s what my PR linked above does, for example). So if you had no problem running the withTracker HOC on the server, I don’t think a useTracker hook will cause more issues.

Not sure how the other hooks used by your components will behave on SSR, since that’s not implemented yet in React.

Tracker is not the problem, but yielding functions are.

renderToString(<App />) is no longer synchronous if you use e.g. Collection.find() in one of your components, so another call to renderToString(<App />) might happen before the first one has completed.

if React relies on some globals to keep references for hooks (like they use globals to keep the current value in React.createContext, we will get into troubles, because these references might change because of a concurrent rendering

2 Likes

Sure, what I’m saying is : There are actually no hooks involved on the server. The current implementation of the useTracker hook does nothing more than the withTracker HOC when Meteor.isServer is true : it just runs the callback you give it, once, non-reactively, and not involving any react hooks.

So if your code has no problem currently with withTracker(callback_that_yields) on the server (and I assume that’s the case ?), then it shouldn’t have problems with useTracker(callback_that_yields) either.

Maybe the issue you mention will appear with components using other hooks (useState, useEffect…) directly, but not with useTracker. Definitely worth keeping an eye on, but not really related to the existence of a useTracker hook :slight_smile:

aaah, yes. i referred to the topic here, to react-hooks :wink:

@macrozone right, sorry, I forgot that this thread was initially about “react hooks” in general, and that I later kind of hijacked it with “hey, we can probably have a hook for Tracker data” :slight_smile:

Apparently React 16.6.3 contains a couple fixes around context and SSR. Dunno if they affect the issues your seeing with yields and Fibers ? (or your fix package, for that matter…)

yes, i saw that as well and did a first attemp to upgrade to react 16.6.3. First result is, that SSR is now even more broken then before with meteor :wink:

Yawn. I’m not against incremental improvements. At the same time, this is another one of those changes that only the react maintainers and language purists care about. In the grand scheme of building digital products, whether your declare you component with the word class or not isn’t going to move the needle.

Hooks is more than not needing class components. Hooks provide a smaller building block than a component, as its been. Meaning, as React developers, we can now share and npm install more code than ever before. Think about the state of the community when there is a hook for everything.

Need list filtering/selecting?

 const {toggleOne, isSelected, selectAll } = useList(items)

etc…

2 Likes

Exactly, you can fine some hooks on npm already and the platform is an interesting one.

So essentially it provides a more systematic API to share/re-use more granular code, which is cool.

1 Like

I didn’t see that aspect highlighted yet. Sounds powerful now.

@yched Can you please give an example using useTracker with Meteor.subscribe code?

@a.com something like:

function MyComp(props) {
  const doc = useTracker(props => {
    Meteor.subscribe('my_subscription', props.var);
    return MyCollection.findOne(props.id);
  }, [props.var, props.id]);
  return <div>{doc ? doc.title : 'No document found'}</div>;
}

You can also return an object with several values (like you currently do with the withTracker HOC), for instance if you also want the ‘ready’ status of the subscription:

function MyComp(props) {
 const { ready, doc } = useTracker(props => {
   const sub = Meteor.subscribe('my_subscription', props.var);
   return { 
     ready: sub.ready(), 
     doc: MyCollection.findOne(props.id)
   };
 }, [props.var, props.id]);
 return ready ? <div>{doc ? doc.title : 'No document found'}</div> : <Spinner />;  
}

I’d tend to think a better practice would be to split independant results each into their own useTracker calls, since each reactive func then gets recomputed on its own only when necessary:

function MyComp(props) {
 const ready = useTracker(props => {
   const sub = Meteor.subscribe('my_subscription', props.var);
   return sub.ready();
 }, [props.var]);
 const doc = useTracker(props => MyCollection.findOne(props.id), [props.id]);
 return ready ? <div>{doc ? doc.title : 'No document found'}</div> : <Spinner />;  
}
1 Like

I have just added this to local package directory in a medium sized app using withTracker extensively as a package override for react-meteor-data, and in my not too extensive testing I can confirm, it works pretty well! I’m going to actually deploy this to our testing server and see how it goes.

Is there a Pull Request for this yet? (Er, nm, I found it.)

I’m kind of digging hooks. I made this quick useSubscription hook on top of this:

// bad code, doesnt work
// export const useSubscription = (name, ...rest) => {
//   const [isReady, setIsReady] = useState(false)
//   useTracker(() => {
//     const handler = Meteor.subscribe(name, ...rest)
//     setIsReady(handler.ready())
//     return () => { handler.stop() }
//   }, [name, ...rest])
//   return isReady
// }

/// elsewhere
// const isReady = useSubscription('my-pub', 'arg1', 'arg2')

Pretty spiffy. This is actually untested, but I’ve found it fairly easy to express various hooks, and to do so with much less code than using the old container method. Now I just have to figure out how to make a useMeteorState wrapped around ReactiveVar, so that we can have persistent local state, which survives hot code push!

UPDATE: This code was incorrect. I mixed up the syntax (useTracker’s API is a mix of useSession and useEffect), and made it work like it would if useTracker was like useEffect - but it’s not. Here is a (simpler) corrected version:

export const useSubscription = (name, ...rest) => useTracker(
  () => Meteor.subscribe(name, ...rest).ready(),
  [name, ...rest]
)

/// elsewhere
const isReady = useSubscription('my-pub', 'arg1', 'arg2')
4 Likes

looking forward to it

So it looks like ReactiveVar does not persist through hot code pushes. ReactiveDict does, and Session is a single instance of ReactiveDict in a package. Cheeky. Also, ReactiveDict needs a globally unique ID in order to function correctly, which means we can’t have the API compatible version of useState which survives hot code push (at leas not uing using ReactiveDict) that I was after.

Some other observations:

  • There doesn’t seem to be an instance specific, guid inside React to use for that uniquie identifier, that I can access anywhere. I think there used to be (maybe still is) one, but it is not public, and I don’t think it’s guaranteed to the be the same value between tree builds (page refresh). If this is incorrect, and there is some reliable instance specific ID in React - please let me know!
  • For a direct ReactiveDict hook, we’d need to enforce a guid at the API level. This makes the API challenging for consumers, and I still think we need a better option for the thing to be useful. (If a user were to use the component name, every component of that type would use the same value. They could use the component name + some unique id tied to some data the component is dealing with, but that could mean every instance with both of those would use the same data, and we wouldn’t want that, etc.)
  • Since instance based IDs are impractical for us, we should probably focus on a useSession hook. The implication that every key must be unique is already set for Session, so we can, er, offload that concern to the user. This is actually probably the easiest to implement - we can just use withTracker, and access the Session API directly.
  • Another option would be to use our own custom hook entirely - don’t even bother with ReactiveDict, and produce a custom persistence layer using Meteor’s Reload package.
  • Of course another option would be to leverage one of React’s popular state managers, like Redux and maybe write a custom middleware built around Meteor’s Reload package - or just use one of the various existing offline middlewares.

That’s a lot to think about I suppose! I’m going to use Session in the short term. A solution for something like temporary form data would look something like this:

import { Session } from 'meteor/session'

export const useSession = (name, defaultValue) => [
  useTracker(() => {
    // Session.setDefault prevents resetting the value after hot code push
    Session.setDefault(name, defaultValue)

    return Session.get(name)
  }, [name, defaultValue]),
  (val) => Session.set(name, val)
]

// elsewhere
const [myVar, setMyVar] = useSession('mySessionVar', 'initial-value')

A couple of notes:

  • I had originally tried cleaning up the Session value with useEffect(() => () => Session.delete(name)) but it didn’t work. I’m not sure I understand how to use that well enough yet.
  • Funky things happen if you change name or defaultValue. The setter you get back (setMyVar in the example) stays locked with the previous value. There is some info in the hooks manual about this - and it is expected behavior - it’s just funky. I did some testing using unHooked setTimeouts, and ran into these issues - started to feel a LOT like Meteor coding when not properly using tracked functions (there are some useTimeout hook examples out there). A proper implementation of this should warn the user if they try to change either of those values.

Some opining:

I wonder if it would make sense to wrap some of these hooks into a new package (react-meteor-hooks), rather than trying to replace the old stuff in react-meteor-data. There’s a ton of old code in that old package, and I would hesitate changing any of that. It worked well enough in my limited testing to replace withTracker with this hooks based one (well, from the updated one in the PR), but it did seem to make my app behave a little differently - like it painted differently (this is completely subjective, and maybe not even accurate). Additionally, there’s a bunch of stuff in there we don’t need, so why not take the opportunity to do a clean break? The old package is also eagerly loaded, and it may make a mess to try to get folks to update to newer react version, etc. Just some thoughts.

If the goal is to have a global reactive state which survives hot code push, we can combine Session with reactn. reactn will provide hooks and helpers to access/set the state. All we have to do is initiate the reactn state from Session and update the Session whenever the reactn state changes:

import { addCallback, setGlobal } from 'reactn'
import { Session } from 'meteor/session'

const initState = {
  foo: 'bar',
}

// this will execute whenever the reactn global state changes
// update the Session as well.
addCallback(state => {
  Session.set('globalState', state)
})

// set the default Session
Session.setDefault('globalState', initState)

// set reactn's initial global state from Session
// which survived hot code push
setGlobal(Session.get('globalState'))

Then inside a react functional component, we can simply do:

const [foo, setFoo] = useGlobal('foo')

Also, I’m not sure I fully understand your comment about the funky thing, but have you read this post about Dan’s useInterval hook?

1 Like

That looks similar to what I mentioned above about creating a custom middleware for redux - similar idea, except reactn gives a hook api more similar to the session API I set up. I hadn’t heard of reactn before (there are so many of these!) This implementation looks similar to what I did, with a little more redux style indirection with setting up the default value.

The funky thing is that the setVar callback you get from the hook is bound to the specific state of a specific run of render (or in this case, since it’s memoized, the state of those two variables). It’s mentioned in the react hooks docs, and it’s not unexpected, it’s just a little bit funky. I don’t know if I saw this post, but I did read another that had a hooks based setTimeout implementation (and also explained the funkiness better than I did).

reactn feels very “natural” alongside useState, and if you need more complexity, you can use reducer functions. I don’t think global state management can be simpler :slight_smile:

2 Likes