Skip to content
Advertisement

having n states in react, assuming that n won’t be received in props

How could I have n states in a React component

Assuming that the component won’t receive this n value in any props, is something that it will get from a database

Using useState will create the state, setState for each pair, but I need n pairs

Rafael

Answer

JavaScript arrays doesn’t have a fixed length. You can do something like

const [arr, setArr] = useState([]); 

And when you receive n values from database just set it to the array using setArr(values)

Now arr will be an array containing n elements retrieved from database. You can then iterate over it and render them as you wish.

Advertisement