Skip to content

Respond to prop changes with side effect #98

Open
@OliverJAsh

Description

@OliverJAsh

Sometimes we want to use an observable not to create state but rather just to perform side effects.

This is possible using useObservable:

import React from 'react';
import { EMPTY } from 'rxjs';
import { useObservable } from 'rxjs-hooks';
import { map, mergeMapTo, tap } from 'rxjs/operators';

declare const sideEffect: (number: number) => void;

const MyComponent: React.FC<{ foo: number }> = props => {
  useObservable(
    input$ =>
      input$.pipe(
        map(([foo]) => foo),
        tap(sideEffect),
        mergeMapTo(EMPTY),
      ),
    props.foo,
    [props.foo],
  );

  return <div>Hello, World!</div>;
};

… but it's a bit awkward for a few reasons:

  • We are forced to return an Observable of a certain type (State), when the type doesn't matter to us, since the result is not being used outside of the hook. We need to do mergeMapTo(EMPTY) at the end of the chain, to satisfy the return type.
  • We are forced to provide an initial state, but again we are not using State here.

What do you think about another hook which is specifically designed for this use case, to avoid the problems above?

useObservableSideEffect(
  input$ =>
    input$.pipe(
      map(([foo]) => foo),
      tap(sideEffect),
    ),
  [props.foo],
);

I'm sure we can find a better name… 😄

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions