Reset the useState to initial state in ReackJS Hooks

i have got three option buttons and basically i am looking when one button is clicked the other two will reset to default , at now it is working but i have to manually set the state of other two but i guess there might be a better solution to reset, any thoughts on this guys Thanks

 function Home({ userData, userstatus }) {
  const [yogaMatState, setYogaMatState] = useState("---Select Yogamats---");
  const [yogaPropsState, setYogaPropsState] = useState(
    "---Select YogaProps---"
  );
  const [accessoriesState, setAccessoriesState] = useState(
    "---Select Accessories---"
  );

  function yogaMatSelected(e) {
    setYogaPropsState("---Select YogaProps---");
    setAccessoriesState("---Select Accessories---");
    setYogaMatState(e.currentTarget.textContent);
  }
  function yougaPropsSelected(e) {
    setYogaMatState("---Select Yogamats---");
    setAccessoriesState("---Select Accessories---");
    setYogaPropsState(e.currentTarget.textContent);
  }
  function Accessoriesselected(e) {
    setYogaMatState("---Select Yogamats---");
    setYogaPropsState("---Select YogaProps---");
    setAccessoriesState(e.currentTarget.textContent);
  }

with manually i mean i have to set the other two buttons state like this in case of yogamatselected(e) is executed it will rest the state of other two back to initial values but i have to type in the initial values like this…

function yogaMatSelected(e) {
    setYogaPropsState("---Select YogaProps---");
    setAccessoriesState("---Select Accessories---");
    setYogaMatState(e.currentTarget.textContent);
  }

I don’t think there’s a whole lot you can do, especially with only 3 options. You could have a single call that resets them all, then call that for each handler, setting the individual value after that. But ultimately, you’re not saving yourself any code because it ends up being the same number of lines (plus adds a function).

  function reset () {
    setYogaPropsState("---Select YogaProps---");
    setAccessoriesState("---Select Accessories---");
    setYogaMatState("---Select Yogamats---");
  }
  function yogaMatSelected(e) {
    reset();
    setYogaMatState(e.currentTarget.textContent);
  }
  function yougaPropsSelected(e) { // <-- typo with "u"?
    reset();
    setYogaPropsState(e.currentTarget.textContent);
  }
  function Accessoriesselected(e) {
    reset();
    setAccessoriesState(e.currentTarget.textContent);
  }

It is a little less redundant, though, so if you need to update a default value, you only need to do it in one place.

1 Like

@senocular i thought earlier that there might be something similar like …rest.setYogaPropsState() but i guess there isnt.
you right reset() function wont make much difference although i think it might help avoiding any typos if i place all at one place under reset function. Thanks mate :+1: