passing props from pages to a component where its in different file

Viewed 193

I am using NextJS and trying to get use to it.
I have a index.js page, in that I have 6 components where i imported them from a file outside of pages file.
My main question is that is this the best practice ? this is working fine for development, but what about production ? Should I switch to ContextAPI for this ? Which one is better for performance and SEO ?

File Structure;

/pages
  -index.js
   ...
...
/components
  -Hero.js
  ...

I have queried my database to get hero section's content and passed it as props to index.js in pages as follows;

export const getStaticProps = async () => {
  const { db } = await connectToDatabase();

  const getPagesFromDB = await db.collection('pages').find({}).toArray();
  const getPages = await JSON.parse(JSON.stringify(getPagesFromDB));

  const getHeroContent = getPages.filter((data) => data.section === 'hero');

  return {
    props: {
      getHeroContent,
    },
    revalidate: 1,
  };
};

export default function Home({ getHeroContent }) {
   
  console.log(getHeroContent);

  
  return (
    <>
      <Hero getHeroContent={getHeroContent}></Hero>
       ...
    </>
  );
}

Then did set getHeroContent prop as directly to the react state in Hero.js component as follows;

const Hero = ({ getHeroContent }) => {
  const classes = useStyles(); 
  const [heroTitle, setHeroTitle] = useState(getHeroContent.title);
  const [heroImg, setHeroImg] = useState(getHeroContent[0].image[0].secure_url);
 

 
  
  return (
    <Box component='div' className={classes.root}>
      <div className={classes.hero}>
        <div className={classes.imgWrapper}>
          <Image
            src={heroImg}
            className={classes.img}
             
            layout='fill'
            objectFit='cover'
          ></Image>
        </div>
        <div className={classes.heroTypos}>
          <Typography variant='h2' className={classes.Typo1}>
            {heroTitle}
          </Typography>
          <Typography variant='h5' className={classes.Typo2}>
            <Link href='#!'>
              <a className={classes.Typo2Link}>
                Shop Now &nbsp;
                <ArrowForwardIosIcon className={classes.Typo2Icon} />
              </a>
            </Link>
          </Typography>
        </div>
      </div>
    </Box>
  );
};

export default Hero;
1 Answers

Having a components-folder in the root of the project and importing the components to your pages is a very typical way of doing things with NextJS.

I don't think there are obvious benefits to switching to ContextAPI in this case. Maybe if you need to pass the values very deeply to many components. It's more a question of personal preference. But remember that all context consumers will re-render when the context value changes, which could cause performance issues in a larger app.

Related