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

208
Visualizações
context is not behaving properly in react. printing default values

I created below context in react.

NameContext.tsx

import { createContext } from 'react';
export  const AppContext = createContext("NA"); 

I used this context inside my Layout.tsx . I am using inside Layout because I have some business logic to execute. based on that isActive value will be set.

const [isActive,setIsActive]=useState("NO");
return(
    <AppContext.Provider value={isActive}>
             <User/>
     </AppContext.Provider> 
)

now under User.tsx I am accessing this tab.

import { useContext } from "react";
import { Link } from "react-router-dom"
import { AppContext } from "../context/NameContext";

const User = ()=>{

 const context = useContext(AppContext);
  let isActive:any;

 if(context=="YES")
  isActive=true;

  else
  isActive=false;

  console.log("context is:"+context);
  console.log(isActive);
  
    return(
        <>
                  <span>
                 {isActive && <Link to="user" > List of Users</Link> } 
                  </span>

          </>        

    )
}
export default User;

in just one page refresh it is delivering values many times and most of the time default values. I dont want default values but the value which I set in provider. how can I avoid this abnormal behaviour.

enter image description here

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

0

create a wrapper then put the Layout inside the Wrapper component, the value will be available globally.

//Wrapper
 import React, { useState } from "react";
 export const Context = React.createContext();
 const Wrapper = (props) => {
 const [active, setActive] = useState('NO');
 function changeValue(value) {
  setActive(value)
  }
 function getCurrent() {
   return active;
  }
return (
<Context.Provider value={{ active, changeValue, getCurrent }}>
    {props.children}
</Context.Provider>
);
};

export default Wrapper;

// index.tsx
import Wrapper from './path/Wrapper'
<Wrapper>
  <App />
</Wrapper>

//Layout must be inside App!
//Layout.tsx
import { Context } from "../../layout/Wrapper";
export default function Layout(){
  const context = useContext(Context);
  console.log(context.getCurrent()) // NO
  context.changeValue('YES')
  console.log(context.getCurrent()) // YES
}
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