Home > Back-end >  Maintaining Multiple state values in a Custom React Hook
Maintaining Multiple state values in a Custom React Hook

Time:10-08

I'm looking for a clean way to store several simple values in a custom react hook. It feels uncomfortable to have to return multple setters and getters. I could pass in one value for each, that is const modalState = useState(false) then reference modalState[0] and [1] but that feels odd to. What I don't like about my function below is it returns 10 values. That seems like a lot.

function useNotesModal() {
  const [showModal, setShowModal] = useState(false);
  const [modalNoteId, setModalNoteId] = useState(0); // if 0, means create note in modal
  const [modalNoteTitle, setModalNoteTitle] = useState("");
  const [modalNoteDescription, setModalNoteDescription] = useState("");
  const [modalNoteTagIds, setModalNoteTagIds] = useState([]);

  return {
    showModal,
    setShowModal,
    modalNoteId,
    setModalNoteId,
    modalNoteTitle,
    setModalNoteTitle,
    modalNoteDescription,
    setModalNoteDescription,
    modalNoteTagIds,
    setModalNoteTagIds,
  };
}
export default useNotesModal;

CodePudding user response:

One possible approach would be to just use a single object to hold the state, and return a setter for that object.

Something like:

function useNotesModal() {
  const [state, setState] = useState({
    showModal: false,
    modalNoteId: 0,
    modalNoteTitle: "",
    modalNoteDescription: "",
    modalNoteTagIds: [],
  });
  

  function setFieldState(fieldName, value){
    setState({...state, [fieldName]: value});
  }

  return [state, setFieldState];
}

// Then, to use:

const [modalState, setModalState] = useNotesModal();

const showModal = modalState['showModal'];

setModalState("showModal", true);

The key in this case is to ensure you return a new object every time the internal state is updated.

CodePudding user response:

You can batch the returned values, for example - as values, and actions:

function useNotesModal() {
  const [showModal, setShowModal] = useState(false);
  const [modalNoteId, setModalNoteId] = useState(0); // if 0, means create note in modal
  const [modalNoteTitle, setModalNoteTitle] = useState("");
  const [modalNoteDescription, setModalNoteDescription] = useState("");
  const [modalNoteTagIds, setModalNoteTagIds] = useState([]);

  return {
    values: {
      showModal,
      modalNoteId,
      modalNoteTitle,
      modalNoteDescription,
      modalNoteTagIds
    },
    actions: {
      setShowModal,
      setModalNoteId,
      setModalNoteTitle,
      setModalNoteDescription,
      setModalNoteTagIds,
    }
  };
}

Another option is to batch them automatically by value and set:

const { useState, useEffect } = React;

function useNotesModal() { 
  const states = {
    showModal: useState(false),
    modalNoteId: useState(0),
    modalNoteTitle: useState(""),
    modalNoteDescription: useState(""),
    modalNoteTagIds: useState([])
  }
  
  return Object.fromEntries(
    Object.entries(states)
      .map(([k, [value, set]]) => [k, { value, set }])
  );
}

const Demo = () => {
  const notesState = useNotesModal();
  
  useEffect(() => {
    setTimeout(() => {
      notesState.modalNoteId.set(101);
    }, 2000);
  }, []);
  
  console.log(notesState);
  
  return <div>{notesState.modalNoteId.value}</div>;
}

ReactDOM.render(
  <Demo />,
  root
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

  • Related