Home > Enterprise >  Variable or React State?
Variable or React State?

Time:11-18

Still trying to understand React state.

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

count changes so it's state.

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;

CodePudding user response:

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>
  );
}

CodePudding user response:

Base on your code, you declared currentSlide as a variable, not a state. So, when currentSlide is updated, re-rendering doesn't occur. If you feel burdened to use currentSlide as a state, you can use useMemo hook instead.

This is an example of using useMemo base on your code.

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

function Home() {
  const [count, setCount] = useState(0);
  const currentSlide = React.useMemo(()=>{
    return slides[count];
  }, [count]);
  
  useEffect(() => {
    // interval incrementing count every 10 seconds
  });


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

export default Home;

CodePudding user response:

i will try to explpain to you the logic behind it in a simplified manner if you are put in a situation where your logic is an "if condition" then you will be using the "STATE" an example to that would be as follows

 if(myState==something){
i will do that
}else{
i will do something else
}

Overall whenever you are using a conditional logic you have to use this type of state

  • Related