0

I'm working on a project where the user can create 'things' which I then associate state with.

A simple version of how I am doing this is basically:

function App() {
   const [things, setThings] = useState({})
}

Unfortunately things ends up being a fairly large and heavily nested (at least a few layers deep anyways) object.

something like this:

{
  things: [
      {
         field1: 'value1',
         field2: {...}
         ...
      },
      ...
   ],
   otherThings: ...
}

I know it is not ideal to store so much in one hook, especially since different parts of it will be basically being constantly updated.

So my question is basically: Is there some way where I can dynamically add different useState hooks, so that my state management looks more like:

   const [thing1, setThing1] = useState({...})
   const [thing2, setThing1] = useState({...})
   const [otherthing1, setOtherthing1] = useState({...})

With different useState hooks being added or removed based on user actions?

1 Answer 1

2

Hooks cannot be conditional and should only be called at the top level. React recommends using multiple states and grouping states that change together. If your state is truly really large (being nested doesn't make it large, total size does) you can use browser storages like localstorage or indexedDB to prevent the browser from using too many resources and crashing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.