Search code examples
javascriptjsonreactjsreduxnormalizr

Should you denormalize normalized Redux state before using it in React UI?


I've recently started using Normalizr library, to normalize API responses for Redux state and few parts are still confusing to me.

When using normalized Redux state for UI rendering, passing it to components requires additional id props, and just defining props gets much more complicated

           {postIds.map((postId) => (
            <Post
              postText={entities.posts[postId].body} 
              commentIds={entities.posts[postId].comments}
              postComments={entities.comments}
              postAuthor={
                entities.users[entities.posts[postId].author.username]
              }
            />
          ))}

Should you denormalize data before using it in React UI ?
Or is this a normal pattern ? And if so, is there any way to simplify it ?


Solution

  • Yes, when using normalized state, you would normally only pass an item ID to the child component, and let it look up its own data using that ID prop:

    const TodoListItem = ({ id }) => {
      // Call our `selectTodoById` with the state _and_ the ID value
      const todo = useSelector(state => selectTodoById(state, id))
      const { text, completed, color } = todo
    
    }
    

    I'd also suggest reading through: