BrainFRZ
BrainFRZ

Reputation: 407

Can the updater function in useState be redefined in React?

I'm working on a rather complex component that uses a store object. The data is local, so it doesn't warrant being added to my Redux store, but expensive enough that it shouldn't be calculated every render. I'm using useState to store and update this object. However, I have several functions regarding the store that I'd like to break out into a new file, including the updater function. For example, I'd like to do something akin to this:

import { storeUpdater } from './ComponentStore.js';
function MyComponent(props) {
  const updateStore = storeUpdater;
  let storeState = useState({});
  const store = storeState[0];
  storeState[1] = updateStore;
  ...
}

Would this reliably work, and, more importantly, is it breaking any rules/anti-patterns?

Upvotes: 1

Views: 406

Answers (1)

giotskhada
giotskhada

Reputation: 2452

This shouldn't work. You're just re-assigning storeState[1], which you defined, to a different function, other than setState provided by useState. This code shouldn't update your storeState[0] at all.

Instead, you should make your storeUpdater function take setState function as an argument and provide it in this component.

function storeUpdater(setState) {...}

const updateStore = () => storeUpdater(storeState[1])

And then, inside your updateStore, do the desirable modifications to the storeState and then pass the new state to setState. If the new state depends on the previous state, you can use setState(prevState => nextState) syntax.

Upvotes: 1

Related Questions