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