blackhole://nilFM

reversing react data flow

Sometimes in React you need to bubble some state up from a child component to its parent, and you don't want to use Redux. This is my preferred method:

// declare the state and wrap it in the parent
const [thingEnabled, setThingEnabled] = useState(false);
const thing = {
  enabled: ()=>thingEnabled,
  setEnabled: (val)=>setThingEnabled(val),
}

// now you can pass it as a prop to whatever disparate children need it
<UsesThing thing={thing}/>
<SetsThing thing={thing}/>