merisbahti / klyva

A state management library that follows the React component model
MIT License
55 stars 4 forks source link

feature(react-utils): Add useCreateAtom hook #38

Closed quaderi closed 3 years ago

quaderi commented 3 years ago

Many times in React you want to create a new atom when inside a function component (based on things like the initial props).

Klyva does not currently make this very ergonomic and people don't always realize that it can be achieved just using useState. Using useState directly might also open the door to people accidentally using the setState functionality that comes from it and thus changing the atom reference when it's not desirable.

As a result of related confusion, atoms are often created with optional values outside of the react component where you don't have access to the props/relevant information.

This new useCreateAtom hook would return a newly created atom, providing an idiomatic and more obvious way of achieving this result. (Similar in spirit to howuseRef wraps useState)

The hook would simply need to be passed a function that, when called with no arguments, produces the initial value for the atom.

e.g. you could do things like this

import * as React from 'react'
import { Atom, useCreateAtom } from 'klyva'

import { OtherComponent } from './other-component'

export const SomeComponent = ({ min, max }: { min: number, max: number }) => {
  const randomAtom: Atom<number> = useCreateAtom(
    () => Math.random() * (max - min) + min
  )
  return <OtherComponent randomAtom={randomAtom} />
}

TODO:

codesandbox-ci[bot] commented 3 years ago

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 28f6965b658e0fdcfcacf974c86cc139df9becb1:

Sandbox Source
React Configuration
React Typescript Configuration
merisbahti commented 3 years ago

Do we wanna merge this now, do tests/docs later?

quaderi commented 3 years ago

Why not?

krawaller commented 3 years ago

I'm very late here, but - neat addition, @quaderi! 👯