Effect CommunityEC
Effect Community2mo ago
8 replies
harrysolovay

Simplifying useEffect with useAtomSet in React Component

Hoping for guidance around how to simplify the following / get rid of the useEffect gunk:

import { Atom, useAtomSet } from "@effect-atom/atom-react"
import { createFileRoute } from "@tanstack/react-router"
import { Effect, Schema as S } from "effect"
import { useEffect } from "react"

const validateSearch = S.Struct({
  _restore: S.Boolean.pipe(S.optional),
}).pipe(
  S.decodeSync,
)

const restoreAtom = Atom.fn<boolean>()(Effect.fn(function*(restore) {
  if (restore) {
    // ...
  } else {
    // ...
  }
}))

export const Route = createFileRoute("/id")({
  ssr: false,
  validateSearch,
  component: () => {
    const { _restore } = Route.useSearch()
    const restore = useAtomSet(restoreAtom)
    useEffect(() => {
      restore(_restore!!)
    }, [_restore])
    return <div>...</div>
  },
})
Was this page helpful?