score:5
yeah, what you're describing is what you have to do if you store normalized state and then want your components to consume an array.
usually, my state will be something like this:
users: {
byid: {
// map of objects keyed by id
},
ids: [//array of ids],
}
note that i'm keeping ids around to keep track of the order the items were returned from the server; that may or may not be necessary depending on the use case. you may be able to just store the object and use object.keys if the order is not important (probably because you end up sorting by some other criteria).
typically, the most consumable form of the data will be an array, so you would define a selector to get the users. following the pattern of colocating reducers and selectors, you would have
// user reducer
export const getusers = (state) => state.ids.map(id => state.byid[id])
and
// root reducer
import users, * as fromusersreducer from './users
const reducer = combinereducers({
users,
})
export const getusers = (state) => fromusersreducer(state.users)
and then your container
import { connect } from 'react-redux'
import { getusers } from 'reducers/root'
import userscomp from './users
const mapstatetoprops = (state) => ({
users: getusers(state),
})
export default connect(mapstatetoprops)(userscomp)
in terms of whether this conversion is a reasonable cost or not, it depends on the use case. where normalized state shape gets to be really important is when you're data can be edited, or your data is related to other pieces of data (getting all posts from a user etc.). if, however, all you're doing is getting a list of data and all you ever do with it is just display that list, then normalizing is probably not necessary.
if you end up needing to add more complex operations for the data down the line, it is easy to switch assuming you are being strict about only accessing state via selectors. normalized data is generally seen as a best practice simply because you generally are going to end up doing more complex things with your data where having a normalized shape is advantageous. but it's not a hard rule or anything; there are cases where it's not needed for sure.
the only real costs you are looking at here is
- code to perform the normalization/denormalization.
- performance hit if your lists are very long, having to denormalize on every render of a container.
you can mitigate the performance hit pretty easily using reselect. this is oftentimes not necessary. in terms of the extra code, it's basically the same sort of stuff over and over again, so it can be pretty easy to abstract, and the code itself is really not complicated anyways. it's a lot less complicated than reducer/selector code would be in a complex app if everything were stored as arrays.
Source: stackoverflow.com
Related Query
- Must normalizing state shape for array data involve round-trip conversion between object array and nested object
- How can i get array of object from this data for state and count in reactjs
- I am trying to set data in state everytime on first index for react in array of object
- Need a solution to fetch data from array and then push it to state using for each
- How to set State Array variable for form Data
- After useEffect API call, state set by useState for json data being passed to a component as props returns empty array
- Data conversion for prime react data table component from array to JSON?
- React-Redux State Shape for multiple pages
- How can I share state data between components using custom hooks?
- React's setState(), data mutation for nested structures, why not modify state directly?
- Providing initialValues for an array in final-form-arrays causes state changes to reset the whole form, how can i prevent this?
- React - Combine data returned two api calls and set state of an array with these values
- Redux state shape for managing multiple React component instances?
- Better/faster way for changing React array state than cloning it?
- how to display and map the first id of an state or const data array objects?
- add the data every time the funtion is called into a array object of State
- Taking React State (object of objects(example inside)) and getting an array of objects to map() for component rendering
- ReactJS iterate through state array with dynamic key with its data
- How Do I Pass a Function Through A React Component For Data Sharing Between Parent and Child?
- using state value in state data for apex charts within react app
- Sending state for an Axios POST and data not showing in req.body
- angular scope vs react state how does it work for data binding
- Why state doesn't keep all the data in Array state in hook when it updated in foreach?
- react-hook-form: idiomatic approach for two-way mapping between form state and input state
- Use local state for forms when data is in redux
- ReactJS: How to add a new element in array state and to preserve "prevState" for them?
- How to add data to redux state array without any id in a reducer?
- How can I watch for state of data in redux container, when I want to sort or filter it?
- TypeError when making Columns for React-Table using array of objects as Data
- Filtering data for more visualization of data in react-chartjs-2 when you have lot of array element
More Query from same tag
- Question related to previous state implementation using react hooks
- (S)CSS Flexbox Justify-Content: Flex End Not Applying
- Can I send an AJAX call in React and Redux without action creators and reducers?
- How to get Server connected?
- Material UI this.state error for color background
- React - Dynamic background colors to parent and child
- Async/Await is not working as expected : ReactJS+ Async Await
- react property yyy is missing in type 'yyy' but required in type 'zzz'
- Next.js how to implement react-google-recaptcha in my contact form
- How to pass selected items data to another component React
- Why use `useTable` over `ReactTable` when using react-table
- React - How to break a line in a cell of a material ui table
- Webpack 4 Code splitting generating separate vendor files for each route
- Show search results from api call - only showing in Console - React
- Hold off React Render until after request
- Cannot display switch in tabs in material-ui
- How can I scroll right when inserting a character in draft js?
- How to integrate API in ReactJS?
- React Router Route does return anything
- How to call function from App.js file inside public folder in React JS
- Why does my component show as Anonymous in React components dev tool
- React Superagent-bluebird-promise with headers
- Get specific value from array of objects [{"key":"value"}, {"key":"value"}]
- React Context Not Updating Globally
- Mongodb updated password is not saved into the database
- componentWillMount warning on function that setState
- Unable to pass function in props to a Component | React
- React test componentWillReceiveProps using enzyme
- How to stop the previous component from rendering when it is redirected to another component in react
- Execution failed for task ':app:compileDebugJavaWithJavac'. > Could not find tools.jar