Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda