How to handle creating hooks dynamically on event handler function

35 views Asked by At

I am quite new to React and stumped on the best way to implement a form with the need for persistent storage of some filters. There are 10 different categories in the form, and each category has a different set of filters that need to be persisted independently across the application upon submitting the form. I am using const [storedFilter, setStoredFilter] = useAtom(selectedAtom); to access and set the filters. However, since the category is only determined on submission of the form, I am unable to determine what selectedAtom is beforehand. From what I understand, hooks should also not be called/ initialised in event handlers. What is the best way to implement this (not sure if I would need to create 10 separate hooks in advance)? Any advice would be much appreciated!

1

There are 1 answers

2
Vaibhav Nigam On

If selectedAtom is expected to be determined at a later stage, you should create a new state variable for it.

const [selectedAtom, setSelectedAtom] = useState(); // pass initial value, if any

const [storedFilter, setStoredFilter] = useAtom(selectedAtom);

// event handler
const eventHandler = (evt) => {
  setSelectedAtom(newValue); // derive newValue from event
};

I assume useAtom hook updates storedFilter based selectedAtom passed as argument.