Home > Software engineering >  How to reuse a const object between pages in React?
How to reuse a const object between pages in React?

Time:02-04

I'm using this snippet below to translate my website content. However, there's a way to avoid copying and pasting this code between pages?

import SampleSection from "../section/sample"
import { useRouter } from 'next/router'
import en from '../locales/en'
import pt from '../locales/pt'

export default function Home() {

    const router = useRouter()
    const { locale } = router
    const t = locale === 'en' ? en : pt

    const changeLanguage = (e) => {
       const locale = e.target.value;
       router.push({ pathname, query }, asPath, { locale: locale })
    }

    return (
        <>
            <SampleSection
                title={t.home.title}
            />
        </>

    )
}

CodePudding user response:

Complementing what Justin Formentin said, you'll need to name the hook as useABC where ABC is the name you wanna use.

CodePudding user response:

This is a good opportunity to create your own hook. Basically just extract that logic that you'd need to re-use, stick it in a function and export it. Then you can call it as a hook in as many components as you need to.

More information about creating your own hooks can be found here https://reactjs.org/docs/hooks-custom.html.

  •  Tags:  
  • Related