How to Group State and Pass it Down to Children with React Hooks

import { useState } from 'react'
export default function Card(){
const [cardNumber, setCardNumber] = useState('')
const [cardNumber2, setCardNumber2] = useState('')
const [cardNumber3, setCardNumber3] = useState('')
const [cardNumber4, setCardNumber4] = useState('')
const [cardNumber5, setCardNumber5] = useState('')
const [cardNumber6, setCardNumber6] = useState('')
const cardState = {
cardNumber, setCardNumber,
cardNumber2, setCardNumber2,
cardNumber3, setCardNumber3,
cardNumber4, setCardNumber4,
cardNumber5, setCardNumber5,
cardNumber6, setCardNumber6
}
return(
<>
<CardNumber
cardNumber={cardNumber}
setCardNumber={setCardNumber}
cardNumber2={cardNumber2}
setCardNumber2={setCardNumber2}
cardNumber3={cardNumber3}
setCardNumber3={setCardNumber3}
cardNumber4={cardNumber4}
setCardNumber4={setCardNumber4}
cardNumber5={cardNumber5}
setCardNumber5={setCardNumber5}
cardNumber6={cardNumber6}
setCardNumber6={setCardNumber6}
/>
</>
)
}
import { useState } from 'react'
export default function Card(){
const [cardNumber, setCardNumber] = useState('')
const [cardNumber2, setCardNumber2] = useState('')
const [cardNumber3, setCardNumber3] = useState('')
const [cardNumber4, setCardNumber4] = useState('')
const [cardNumber5, setCardNumber5] = useState('')
const [cardNumber6, setCardNumber6] = useState('')
//Set all of the state variables and functions to the cardState object
//We are using the "Object Literal Property Value Shorthand" from JS ES6 below (we don't need to pass the {property:value} pair when assigning the object properties - just the variable name, and the key is automatically set to be the variable's value)
const cardState = {
cardNumber, setCardNumber,
cardNumber2, setCardNumber2,
cardNumber3, setCardNumber3,
cardNumber4, setCardNumber4,
cardNumber5, setCardNumber5,
cardNumber6, setCardNumber6
}
return(
<>
<CardNumber
cardState={cardState}
/>
</>
)
}
// CardNumber Child Component:
export default function CardNumber({
cardState,
}){
//Destructure all of the state variables and functions in the child component!
const {
cardNumber, setCardNumber,
cardNumber2, setCardNumber2,
cardNumber3, setCardNumber3,
cardNumber4, setCardNumber4,
cardNumber5, setCardNumber5,
cardNumber6, setCardNumber6
} = cardState
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store