Learn React The Hard Way: Manage State Better

papercoding22

Paper Coding

Posted on November 5, 2023

Learn React The Hard Way: Manage State Better

I've accumulated five years of hands-on experience with React, and I'm excited to share the invaluable insights I've gained to enhance the quality of your React code in real-world scenarios.

Working with Modals

Have you encountered a situation where your web page required numerous modal popups, and wondered about the best approach to handle their states effectively?

Modals

I used to manage modal states in a similar manner, and here's how I used to handle the code for modal state management. Let's assume we are developing a User Management feature, and here's a UI mockup of what it looks like:

Users

When users need to perform actions such as creating a new user, editing, or deleting, the page displays a corresponding modal to facilitate these operations. Here's my previous approach to coding for modal state management:

const UserManagement = () => {
  const [showModalCreate, setShowModalCreate] = useState(false)
  const [showModalEdit, setShowModalEdit] = useState(false)
  const [showModalDelete, setShowModalDelete] = useState(false)
  const [showModalAddGroup, setShowModalAddGroup] = useState(false)
    const [targetUser, setTargetUser] = useState()

  const onCreateButtonClick = () => setShowModalCreate(true)
  const onEditButtonClick = () => setShowModalEdit(true)
  const onDeleteButtonClick = () => setShowModalDelete(true)
  const onAddGroupButtonClick = () => setShowModalAddGroup(true)

  const onHideModalCreate = () => setShowModalCreate(false)
  const onHideModalEdit = () => setShowModalEdit(false)
  const onHideModalDelete = () => setShowModalDelete(false)
  const onHideModalAddGroup = () => setShowModalAddGroup(false)

  return (
    <div>
      <ListUser onUserItemClick={setTargetUser} />
      <ModalCreateUser show={showModalCreate} onHide={onHideModalCreate} />
      <ModalEditUser show={showModalEdit} onHide={onHideModalEdit} />
      <ModalDeleteUser show={showModalDelete} onHide={onHideModalDelete} />
      <ModalAddGroup show={showModalAddGroup} onHide={onHideModalAddGroup} />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

As you can see the code above, each modal has its unique state, and when dealing with multiple modals, this could lead to the creation of numerous states, resulting in suboptimal code and redundancy.

This prompted me to reevaluate my approach and, through some challenging experiences, I learned the importance of refactoring my old code to achieve a more efficient and less duplicated structure.

// 💅 Let's Refactor It !!!

const actionOnUserReducer = (state, action) => {
  const {type, payload} = action
  switch (type) {
    case 'CREATE_USER':
      return {
        ...state,
        mode: 'CREATE_USER',
      }
    case 'EDIT_USER':
      return {
        ...state,
        payload,
        mode: 'EDIT_USER',
      }
    case 'DELETE_USER':
      return {
        ...state,
        payload,
        mode: 'DELETE_USER',
      }
    case 'ADD_GROUP':
      return {
        ...state,
        payload,
        mode: 'ADD_GROUP',
      }
    default:
      return {
        ...state,
        mode: 'VIEW',
      }
  }
}

const UserManagement = () => {
  const [actionOnUser, dispatchActionOnUser] = useReducer(actionOnUserReducer, {mode: 'VIEW'})
  const [targetUser, setTargetUser] = useState()

  const onCreateButtonClick = () => dispatchActionOnUser({type: 'CREATE_USER'})
  const onEditButtonClick = () => dispatchActionOnUser({type: 'EDIT_USER', payload: targetUser})
  const onDeleteButtonClick = () => dispatchActionOnUser({type: 'DELETE_USER', payload: targetUser})
  const onAddGroupButtonClick = () => dispatchActionOnUser({type: 'ADD_GROUP', payload: targetUser})
  const onHideModal = () => dispatchActionOnUser({type: 'VIEW'})

  return (
    <div>
      <ListUser onUserItemClick={setTargetUser} />
      <ModalCreateUser show={actionOnUser.mode === 'CREATE_USER'} onHide={onHideModalCreate} />
      <ModalEditUser
        show={actionOnUser.mode === 'EDIT_USER'}
        user={targetUser}
        onHide={onHideModalEdit}
      />
      <ModalDeleteUser
        show={actionOnUser.mode === 'DELETE_USER'}
        user={targetUser}
        onHide={onHideModalDelete}
      />
      <ModalAddGroup
        show={actionOnUser.mode === 'ADD_GROUP'}
        user={targetUser}
        onHide={onHideModalAddGroup}
      />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

We harness the power of React's useReducer hook and consolidate multiple modal states into a single state. This not only minimizes duplication but also significantly enhances code readability.

💖 💪 🙅 🚩
papercoding22
Paper Coding

Posted on November 5, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related