Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
How to reuse a const object between pages in React?

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}
            />
        </>

    )
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!