JavaScript-React-useEffect

Can someone please help me?
I declared a function stateChange in 3rd code section and it seems to be working fine.
Does I need to use useEffect or not.
Could it be optimized with useEffect

import React from 'react'
import Card from './Card'
import { cards } from './cards'

const InitialCards = () => {
  return (
    <section className="container">
      <Card cards={cards} />
    </section>
  )
}

//  title is used as a key so it should be unique and images can be any anything

export const cards = [
  {
    title: 'Tropical rainforest',
    image: '/images/landscape-tropical-green-forest.jpg'
  },
  {
    title: 'Cat Wallpaper',
    image: '/images/4-47096_cat-wallpaper-background-data-src-free-download-cat.jpg'
  },
  {
    title: 'Maple leaves',
    image: '/images/beautiful-autumn-leaves-autumn-red-background-sunny-daylight-horizontal.jpg'
  },
  {
    title: 'Lake View',
    image: '/images/beautiful-shot-small-lake-with-wooden-rowboat-focus-breathtaking-clouds-sky.jpg'
  },
  {
    title: 'Dark View',
    image: '/images/old-black-background-grunge-texture-dark-wallpaper-blackboard-chalkboard-concrete.jpg'
  }
]
import React, { useEffect } from 'react'

function Card({ cards }) {

  const stateChange = (title) => {
    const panels = document.querySelectorAll('.panel')
    panels.forEach(panel => {
      panel.classList.remove('active')
      if (panel.innerText === title) {
        panel.classList.add('active')
      }
    })
  }

  // useEffect(() => {
  //   stateChange()
  // }, [])

  return (
    <>
      {cards.map(card => {
        const { title, image } = card

        return (
          <div className='panel' key={title}
            style={{ backgroundImage: `url(${image})` }} onClick={() => stateChange(title)}>
            <h3>{title}</h3>
          </div>
        )
      })}
    </>
  )
}

export default Card
/*index.css*/
body {
  display: flex;
  align-items: center;
  padding: 3vh;
  justify-content: center;
}

.container {
  width: 90vw;
  display: flex;
}

.panel {
  height: 90vh;
  border-radius: 30px;
  flex: 0.5;
  margin: auto 10px;
  position: relative;
  transition: flex ease 2s;
  background-size: auto 100%;
  background-repeat: no-repeat;
  background-position: center;
  cursor: pointer;
}

.panel.active {
  flex: 5;
}

.panel.active h3 {
  opacity: 1;
}

h3 {
  position: absolute;
  bottom: 20px;
  left: 10px;
  color: white;
  background-color: black;
  opacity: 0;
  transition: opacity 3s;
}

@media (max-width:700px) {
  .container {
    width: 100vw;
  }

  .panel:nth-of-type(4),
  .panel:nth-of-type(5),
  .panel:nth-of-type(6) {
    display: none;
  }
}

useEffect has a dependency array which tells it when to trigger. In your case it is empty so it only runs when your component initially renders.

Whether you need it or not depends on what your intentions for your code is.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.