avkonst / hookstate

The simple but very powerful and incredibly fast state management for React that is based on hooks
https://hookstate.js.org
MIT License
1.65k stars 109 forks source link

how to fix rerendering of a component when a state is used as a dependency #182

Closed codeidiotpro closed 3 years ago

codeidiotpro commented 3 years ago

here is the code https://codesandbox.io/s/todolist-with-hookstate-n5m37?file=/src/components/TodoList.js check out the code @ line 16 from TodoList component

I have no idea what's going but when I use this state as a dependency it loops forever. I have no idea how to solve this


function component() {
 const stateTodoData = useState(todoData);

 useEffect(() => {
    someFunction();

    // add stateTodoData as dependency but this will rerender the component forever
  }, [stateTodoData]);

}
avkonst commented 3 years ago

stateTodoData gets new proxy instance every rerender, so use effect is triggered each time, which call some other state.set, I assume, which triggers the rerender again and the cycle repeats.

currently there is a limitation that State objects can not be used in dependency lists of useEffect. See https://github.com/avkonst/hookstate/issues/140

however, in most cases, including yours, this is not required. Your effect uses the state value, but not the state object itself. When you obtain the state value and it is of a primitive type, useEffect dependency works correctly. If your state value is of type Object, then attach Downgraded before getting the value AND ensure shallow comparison works for your state value correctly (same as with React.useState data).

avkonst commented 3 years ago

If this is answered too, please close.