0

I am using Next js for an application. The code components have a global state stored in parent and passed down to child components using ReactContext.

In one of the components, when I am trying to create a state component by destructuring a parent state it is behaving in an unpredictable manner. At times the destructuring initializes a local state, at times it does not.

const ContextEntry = () => {
  const { widget, pageStates } = useContext(WidgetContext);

  const { currentLanguage } = pageStates;
  // this statement produces an output..
  console.log("ContextEntry Component widget context  ", widget.context);

  //?? why not getting destructured
  // const [contextEntryData, setContextEntryData] = useState(widget.context);
  const [contextEntryData, setContextEntryData] = useState({
    ...widget.context,
  });
  console.log("State object ", contextEntryData);

  

   return (
    <div className={style.container}>
      {widget.fields.map((field) => {
        return (
          <CustomFieldWidget
            field={field}
            key={field.fieldId}
            updateContextEntry={updateContextEntry}
          />
        );
      })}
    </div>
  );
};

export default ContextEntry;
user3445623
  • 3
  • 1
  • 5
  • is there any strong reason for you duplicating state? this is generally a bad approach. any state change won't be reflected on others components that consumes `widget` context – buzatto Feb 12 '21 at 18:33
  • You haven't shown what your `WidgetContext` does, but your problem appears to be that `useState` doesn't change the state when the `widget.context` changes. This has nothing to do with destructuring. – Bergi Feb 12 '21 at 20:24

0 Answers0