DEV Community

Cover image for Learn React The Hard Way: Manage State Better
Paper Coding
Paper Coding

Posted on

3 1

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.

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay