Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks useState - What recommended, have just one State per component or multiples states? [closed]

What is a better way to optimize and do the code more readable in React using Hooks / Functional components; Having a single setState hook or multiples per component?.

To expand my question, consider the following:

With hooks we can use multiples states, making in someway more convenient the split of the states for specific uses (For example, one state for the user data, another to save the loading flag, other for the data retrieved for an API, etc). In my first steps, I was confident that the best way was had a multiple states per each data that I want to manage... but, after some time, I'm starting to have problems with the synchronization between multiples states when I want to update/read multiples states in a function of an effect (useEffect).

So, I start to believe the best way to manage the state(s) with Hooks it just has a single state using an object and manages all my data from here... Like does the Class Components...

const [data, setData] = useState({
    retrieveData: false,
    apiData: [],
    userInfo: [],
    showModal: false
})

// To update:
setData(oldData => {
    return { ...oldData, showModal: true }
})

// Or:
setData({ ...data, retrieveData: true })

In my opinion, is better have a single state, but this could affect the performance/readability in some way that I not having in consideration?

like image 539
MiBol Avatar asked Oct 29 '19 12:10

MiBol


1 Answers

The React documentation suggests using multiple separate bits of state for things that change independently of one another:

However, instead we recommend to split state into multiple state variables based on which values tend to change together.

(their emphasis)

This plays well with memoization for instance (useMemo, useCallback), so you can indicate that changes to X but not Y invalidate the memoized item. It also plays well with writing your own hooks (see the linked documentation for an example).

like image 70
T.J. Crowder Avatar answered Oct 05 '22 23:10

T.J. Crowder