Search code examples
reactjscallbacksetter

When using a Setter in react how does the callback function argument get named?


I currently have the code snippet below and was wondering how naming conventions work for arguments in a callback function. How is "prevQuestionIndex" related to questionIndex?


export default function QuizNavBar({ questions }) {
  const [questionIndex, setQuestionIndex] = useState(0);

  // define event handlers 
 const goBack = () => {
   setQuestionIndex(prevQuestionIndex => prevQuestionIndex - 1)
 }

Solution

  • When you pass a function to the setter, naming of the parameter of the function doesn't matter in terms of performing the operation correctly. The prevQuestionIndex in this case is always the previous value of the questionIndex. It will behave the same way if you name it banana or fish.

    const goBack = () => {
       setQuestionIndex(banana => banana - 1) //will work just fine, but obviously not that maintainable
     }