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

152
Visualizações
React Context Not Updating Globally

this is my Context, But I can't update its values globally. It does change but not globally, and If I refresh the page for example, it goes to the default values again. What I am doing wrong?

import React, { useReducer } from 'react'

const initialState = {
    user: 'magnus',
    isAuth: false
};

const actions = {
    SET_USER: "SET_USER",
    SET_AUTH: "SET_AUTH"
};

const reducer = (state,action) => {
    switch(action.type) {
        case actions.SET_USER:
            return {
                user: action.user
            };
        case actions.SET_AUTH:
            return {
                isAuth: action.setAuth
            };
        default:
            return state;
    }
};

export const UserContext = React.createContext();

const Provider = ({children}) => {
    const [state, dispatch] = useReducer(reducer, initialState);
    
    const value = {
        user: state.user,
        isAuth: state.isAuth,
        setUser: (user) => {
            dispatch({ type: actions.SET_USER, user});
        },
        setAuth: (auth) => {
            dispatch({type: actions.SET_AUTH, auth});
        }
    };

    return (
        <UserContext.Provider value={value}>
            {children}
        </UserContext.Provider>
    );

};

export default UserContext;
export { Provider };

Im using this on the other component:

const { user, isAuth, setUser } = useContext(UserContext);

    return(
        <div>
        <h3>{user}</h3>
        <h3>{isAuth ? 'ok' : 'not ok'}</h3>
        <button onClick={() => setUser('brutus')}>change</button>
        </div>
    )

It is updating the user but only in this component, If I reload the page for example, it keeps saying 'magnus' instead of 'brutus'.

This is my index.js:

<Provider>
  <App />
</Provider>

App.js:

<BrowserRouter>
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/dashboard" element={<Dashboard />} />
                </Routes>
            </BrowserRouter>

Can someone please help me?

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

0

The problem is you export UserContext twice

export const UserContext = React.createContext();

export default UserContext;

So just keep the 1st one and import into component:

import { UserContext } from './UserContext'

Here is the working example

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