简体   繁体   中英

React hooks - How can i attach a component to a listener with server side rendering?

I would like to attach a component to a listener or create a custom hook for that listener.

On client side i would do it like this:

 useEffect(() => {
    const subscription = observable.subscribe({
      next(value) {
        setValue(value);
      }
    });

    return () => subscription.unsubscribe();
  }, [observable])

Attach the listener with useEffect and unsubscribe it in the return function. But useEffect does not work on server side.

I think this problem can be solved (or has to be solved) on a higher level. If i wait until everything is finished and then run the renderToString function on the server, everything should be up to date. This means:

  • Waiting for all Async Functions that can occur (on the server). So all the data from listeners should be prepared and have a final state.
  • Run the renderToString function. This renders the components and hooks.
  • All the useState hooks will be initialised with the correct values from the listeners.

Afterwards on the client side, where async code can happen and has to be handled, the useEffect hooks will do their job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM