Search code examples
react-context

What does const {value:valueFromContext} = useContext(Context) do?


I am new to react and I came across the following code:

  interface ValueContextProps {
  value?: Object;
  nextValue: (value: Object) => Object;
  }
  const ValueContext = React.createContext<ValueContextProps>({ nextValue: (value) => value });
...

const {nextValue:nextvalueFromContext} = useContext(ValueContext)

So what does nextValue:nextvalueFromContext do? What is getting stored in nextValue?

Also, valueFromContext is used like a function in the code. Something like -

nextValue = nextValueFromContext(value)


Solution

  • If you have an object, then you can destructure the object like this:

    const obj = {key: 'value'}
    
    const {key} = obj // this is destructuring
    
    const {key: newVariableName} = obj // this is the same, but key is given a new name
    
    console.log(newVariableName) // 'value'
    
    const {nextValue:nextvalueFromContext} = useContext(ValueContext)
    

    This will read the value nextValue from context, and rename it to nextValueFromContext