Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
How to share a specific variable between different react components

I have 2 sibling components home and history where home has the following function

//home
function handledata() {
    const key = uuidv4();
    localStorage.setItem(key, JSON.stringify(formdata));
  }

I need to access local storage in the sibling history component so how do i access this key variable there

//history
const [items, setItems] = React.useState([]);
  const handledata = () => {
    localStorage.getItem(key);
  };

Complete code of both files https://github.com/Megahedron69/testrep

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You're best option is to decouple localstorage from both the components & make a it a separate module or a class. Then you can access it in both the files.

Pseudocode

class LocalStorage {

  setItem(key, item) { ... }
  getItem(key) { ... }

}

If you don't want to do that - Lifting the state up is the best possible solution when want to share data between sibling components.

Make a parent component of home & history & use localstorage there.

about 4 years ago · Juan Pablo Isaza Relatório

0

You don't need handledata function in that case. You can just access localStorage without it:

 const data = localStorage.getItem(key);
 // use this data any way you want in the component
about 4 years ago · Juan Pablo Isaza Relatório

0

Ways to share data between states:

  1. The parent component.
  2. Localstorage
  3. Global State management

Local storage is not recommended for this stuff and in your case global state doesn't make sense. Parent state is better in your case.

There are multiple things you can do:

  1. Generate key in parent and share it in both components
  2. Create a state in parent component in parent and then set that state in history
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda