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

132
Visualizações
How to update data from child component to parent component using context api in react?

I have two components app.js and posts.js.

My app.js component

import React, { createContext, useState } from 'react'
import Posts from './components/Posts'

const val = createContext()

const App = () => {
  const msg = 'hi'

  return (
    <div>
      <val.Provider value={msg}>
        <Posts />
      </val.Provider>
    </div>
  )
}

export default App
export { val }

My Posts.js component

import React from 'react'
import { val } from '../App'
import { useContext } from 'react'

const Posts = () => {
  const greet = useContext(val)
  return <div>{greet}</div>
}

export default Posts

I want to update the msg from 'hi' to let say 'hello' from Posts component but I don't know how it can be done can someone plz help me understand that including the flow of how values get changed ? I Thanks

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

0

msg needs to be state:

const App = () => {
  const state = useState('hi')

  return (
    <div>
      <val.Provider value={state}>
        <Posts />
      </val.Provider>
    </div>
  )
}

and then:

const Posts = () => {
  const [greet,setGreet] = useContext(val)
  return (
    <>
      <div>{greet}</div>
      <button onClick={() => setGreet('hello')}>Change to hello</button>
    </>
  )
}

It's helpful to look at context as just a prop from far above that you don't want to keep passing down. It's helpful, because that's all that it is.

A reason to use context instead of a prop:

You've got to pass it down through a lot of components, some of which really don't have anything to do with that prop

A reason not to use context:

You're tightly coupling your component to that context.

It's up to you to decide if the tradeoffs of tight coupling are worth it. Sometimes they are, sometimes they aren't. No hard and fast rules.

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