1

I have a selectedId React state that stores integer values. The state is updated with an id integer, when an item is selected from a list. Once selectedId is set, the user can click a delete button to delete the selected element, after which selectedId should be set back to its initial value again.

What is the recommended default value for selectedId? Should it set to null ( useState(null) and setSelectedId(null) ), or be undefined ( setSelectedId() )

const [selectedId, setSelectedId] = useState();
const handleSelect = id => {
  setIsAlertOpen(true);
  setSelectedId(id);
};
<Button onClick={() => {
  deleteItem(selectedId)
  setSelectedId();
}/>
2
  • 1
    add null as a initial value, that is recommended. Commented Nov 15, 2021 at 12:40
  • 1
    I add zero if it does not be in the id list. Commented Nov 15, 2021 at 12:44

1 Answer 1

2

Create a constant to store the initial value, and when you delete the selectedId restore it your initial value.

const initialValue = null;
const [selectedId, setSelectedId] = useState(initialValue);

const handleSelect = id => {
  setIsAlertOpen(true);
  setSelectedId(id);
};

<Button onClick={() => {
  deleteItem(selectedId)
  setSelectedId(initialValue);
}/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.