DEV Community

nop33.eth
nop33.eth

Posted on

Question regarding best practice on managing state

I am working on an app that presents a list of questions to the user and expects answers. The representation of data is something like this:

const steps = [
  {
    title: "Health",
    question: "How satisfied are you with Health",
    answer: null,
  },
  {
    title: "Career",
    question: "How satisfied are you with Career",
    answer: null,
  },
  {
    title: "Love",
    question: "How satisfied are you with Love",
    answer: null
  },
];
Enter fullscreen mode Exit fullscreen mode

My question is, should I store this whole object in the state, or only store the answers?

In the first case, the code would look something like the following. Here we can see that questions and answers are bundled together, which makes it easier to iterate over them and display them together.

const WheelOfLife = () => {
  const [stepsData, setStepsData] = useState([
    {
      title: "Health",
      question: "How satisfied are you with Health",
      answer: null,
    },
    {
      title: "Career",
      question: "How satisfied are you with Career",
      answer: null,
    },
    {
      title: "Love",
      question: "How satisfied are you with Love",
      answer: null
    },
  ])

  const setAnswer = (index, answer) => {
    const newStepsData = [...stepsAnswers]
    newStepsData[index].answer = answer
    setStepsAnswers(newStepsData)
  }

  return (
    <ul>
      {stepsData.map(step => (
        <li key={step.title}>
          {step.title}: {step.answer}
        </li>
      ))}
    </ul>
  )
}
Enter fullscreen mode Exit fullscreen mode

In the second case, I am following the recommendation of the React docs that says "Does it remain unchanged over time? If so, it probably isn’t state.", but now questions and answers are separated and it becomes a tiny bit more complicated to access the data:

const stepsData = [
  {
    title: "Health",
    question: "How satisfied are you with Health",
  },
  {
    title: "Career",
    question: "How satisfied are you with Career",
  },
  {
    title: "Love",
    question: "How satisfied are you with Love",
  },
];

const WheelOfLife = () => {
  const [stepsAnswers, setStepsAnswers] = useState(new Array(stepsData.length))

  const setAnswer = (index, answer) => {
    const newStepsAnswers = [...stepsAnswers]
    newStepsAnswers[index] = answer
    setStepsAnswers(newStepsAnswers)
  }

 return (
    <ul>
      {stepsData.map((step, index) => (
        <li key={step.title}>
          {step.title}: {stepsAnswers[index]}
        </li>
      ))}
    </ul>
  )
}
Enter fullscreen mode Exit fullscreen mode

Thank you for the feedback!

Top comments (0)