Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable or React State?

Still trying to understand React state.

slides won’t change so it’s not state.

count changes so it’s state.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

currentSlide changes based on count. Should it be state?

Thank you for any help!

const slides = [
  { background: 'blue', heading: 'Hi' },
  { background: 'pink', heading: 'Hola' }
];

function Home() {
  const [count, setCount] = useState(0);
  let currentSlide = slides[count]; // should currentSlide be state?

  
  useEffect(() => {
    // interval incrementing count every 10 seconds
  });


  return (
    <div bg={currentSlide.background}>
    </div>
  );
}

export default Home;

>Solution :

It’s fine to keep it as it is. It is in a way ‘derived’ state, and you can just keep it as a normal variable.

As an example, imagine you wanted to show count multiple times in a page. This would be fine to do:

function Home() {
  const [count, setCount] = useState(0)
  useEffect(() => {
    // increment count 10 seconds
  })

  const count1 = count + 1
  const count2 = count + 2

  return (
    <div>
      <div>{count}</div>
      <div>{count1}</div>
      <div>{count2}</div>
    </div>
  );
}

or, more succintly:

function Home() {
  const [count, setCount] = useState(0)
  useEffect(() => {
    // increment count 10 seconds
  })

  return (
    <div>
      <div>{count}</div>
      <div>{count + 1}</div>
      <div>{count + 2}</div>
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading