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
It is just a naming convention you can break, and use whatever name you want. There is no limitation to that on React side.
Here is how react docs describe it:
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
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: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""
andsetAbc
withf()
. To understand it better, we can even use below syntax: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.