Skip to content

Instantly share code, notes, and snippets.

@seivan
Created April 12, 2020 08:02
Show Gist options
  • Save seivan/e86c3a67bc85cbb1ce09b0ce15ddf048 to your computer and use it in GitHub Desktop.
Save seivan/e86c3a67bc85cbb1ce09b0ce15ddf048 to your computer and use it in GitHub Desktop.

Revisions

  1. seivan created this gist Apr 12, 2020.
    18 changes: 18 additions & 0 deletions app.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    const WithJustAutoRun = React.memo((props: {
    first: Todo;
    second: Todo;
    counter: number;
    }) => {

    const rendered = useObservation(() => {
    return (
    <div>
    <h1>
    Obs: {props.counter.toString() + props.first.completed.toString()}
    </h1>
    </div>
    );
    }, [props]);

    return <div>{rendered}</div>;
    })
    17 changes: 17 additions & 0 deletions lib.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    const useObservation = (
    render: () => JSX.Element,
    dependencies: React.DependencyList = []
    ) => {
    const ref = useRef<JSX.Element>();
    const [tick, setTick] = useState(0);

    useEffect(() => {
    return autorun(() => {
    ref.current = render();
    setTick(tick + 1);
    });
    }, dependencies);

    return ref.current;
    };