DEV Community

Discussion on: I wasn't happy with React useState Hook, so I built my own one and made it Open Source.

Collapse
 
marklai1998 profile image
Mark Lai

I dont understand the propose of this hook
For the stale state problem I think it against react philosophy, the only usage I can think of is to track the re-render of the component? Anyway I won't debate here

But for the implementation, first come to my mind is useRef, but you said it will rerender the component. So I took a look into your code, ultimatly you're just using useState for the re-render, then I just dont see the point of using a fancy "proxy" here. I can just rewrite it with a few line of code

const useAtom = (initialState) =>{
  const refState = useRef(initialState)
  const [state, setState] = useState(initialState)

  return {
    value: refState.current,
    state,
    setState: (newState)=>{
      refState.current = newState
      setState(newState)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

I would like to know whats the real reason for the Proxy here,
May be subscription? useEffect can also act like subscription. Also I want to know how will you use the subscription in real live, your subscribe and unsub needs to wrap in useEffect anyway

Collapse
 
cadienvan profile image
Michael Di Prisco

As per your first point, if you ever needed to delay a setState and then use the new value in the same call stack, you know it's not possible only using the state. Having to use a state + a ref for this situation is just a hack, and I didn't want that. The stale state problem isn't part of React philosophy, it's just a necessary evil.

As per the proxy implementation, I never liked the "setState" function mechanism, I wanted something TRULY reactive. This also answers about your rewrite.

The observer pattern (sub/unsub) is a mechanism that can be very useful for certain use cases, first of all if you need to do something BEFORE React rerenders the component. What if you need to update a second state when the atom updates? A useEffect would need 2 rerenders, 1 for the first state and 1 for the second one, by using the atom you only have 1 rerender instead.

Another important difference in my implementation is the "previousValue", which isn't available in the useState hook.

You brought some good points on the table and I'd love to know if my comment answered your questions and convinced you or if you still have some doubts, I love meaningful discussion.