Christophe
Christophe

Reputation: 28114

Is it correct practice to bypass useState in some scenarios?

I have two states in my React component:

// Selected item state
const [selectedItem, setSelectedItem] = React.useState(null);

// Toggle callout visibility
const [isCalloutVisible, setIsCalloutVisible] = React.useState(false);

I have a reset function to reset my states. To prevent a double re-render, I am bypassing setIsCalloutVisible:

const reset = () => {
  isCalloutVisible = false;
  setSelectedItem(null);
}

Is this the correct approach? Or is there a cleaner way to reset both states in a single re-render?

[edit] thanks for the first comments and reply, and clearly merging both into a single state would help. What I'd be interested to understand is why my current approach is not correct, and what the negative effects are.

Upvotes: 1

Views: 139

Answers (2)

Drew Reese
Drew Reese

Reputation: 202618

Given the following component state:

// Selected item state
const [selectedItem, setSelectedItem] = React.useState(null);

// Toggle callout visibility
const [isCalloutVisible, setIsCalloutVisible] = React.useState(false);

If you wanted to reset both state values in a single callback just enqueue both state updates.

const reset = () => {
  setSelectedItem(null);
  setIsCalloutVisible(false);
}

All React state updates from a single render cycle are batch processed between render cycles and the computed state is returned for the next cycle.

State updates may be Asynchronous & Batched

Upvotes: 1

Sangam Rajpara
Sangam Rajpara

Reputation: 678

You can create something like this

const [data, setData] = react.useState({ 
  isCalloutVisible: false, 
  selectedItem: null 
})
const reset = () => {
  setData({
    isCalloutVisible: false,
    selectedItem: false
  })
}

Upvotes: 2

Related Questions