skip to Main Content

In React, when we use state, we write code like the following:

const [abc, setAbc] = useState("")

In this case, why does "setAbc", start with "set", can any other naming conventions be used? For example, updateAbc

If possible, try to provide reference links to read more.

2

Answers


  1. It is just a naming convention you can break, and use whatever name you want. There is no limitation to that on React side.

      const [abc, setAbc] = useState("")
      const [abc, justSet] = useState("")
      const [abc, updateAbc] = useState("")
      const [abc, change] = useState("")
      const [abc, whatever] = useState("")
    

    Here is how react docs describe it:

    The convention is to name this pair like const [something, setSomething]. You could name it anything you like, but conventions make things easier to understand across projects.

    Login or Signup to reply.
  2. It’s basically a naming convention, and to intuitively understand "why it’s just a naming convention", we need to understand the syntax.

    The code you provided

    const [abc, setAbc] = useState("")
    

    actually uses the concept of array destructuring (as also stated in the offical documentation), the above useState("") function invocation will return an array with a length of two:

    ["", f()]
    

    As you can see on the return array above, the first array element is just the state value, and the second array element is the function to update the state. So what your code will do is assign abc with "" and setAbc with f(). To understand it better, we can even use below syntax:

    const abcState = useState("")
    const abc = abcState[0]
    const setAbc = abcState[1]
    

    As you can see in the code above, they’re technically just normal javascript variables, and you can name it like how you name a normal javascript variable.

    Each time your react component do a render, the above code will be executed again, and on the second time it renders, it will ignore the initial state (if it has been updated), and thus the abc will hold the next state value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search