Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!