Home > Software engineering >  useState in react : how to get each props?
useState in react : how to get each props?

Time:06-04

Im trying to convert a class component to a functionnal component and i need to use useState.

However, in the example on the react doc page : https://fr.reactjs.org/docs/hooks-effect.html, i see const [count, setCount] = useState(0);

What is the point of the 0 ? What to do if the props has several constants i want to retrieve, how am i supposed to know or do which one is which one?

thank you

CodePudding user response:

Lets imagine you have a class component with props like this:

interface IProps {
  foo: string
  bar: number
  baz: Array<string>
}

props: IProps = {
  foo: "foo",
  bar: 5
  baz: ["baz"]
}

There are two way of converting this into hooks, you can either use the whole object or break it down, with the latter being the preferred option.

Using the whole object (assuming you are to initialize it with the default values from snippet above):

const [props, setProps] = useState<IProps>(props) 

and then it can be updated in jsx same as in class components:

setProps(props => { ...props, props.foo: "newfoo" })

While this is going to work, it is better to break it down:

const [foo, setFoo] = useState<string>()
const [bar, setBar] = useState<number>()
const [baz, setBaz] = useState<Array<string>>()

and then the state can be updated separately:

setFoo("newfoo")
setBar(8)
setBaz(["newbaz"])

Notes:

In TypeScript the props has to be initialized with the values to conform with the interface. However, if you prefer not to include default values, you can define you interface like this:

interface IProps {
  foo?: string
  bar?: number
  baz?: Array<string>
}

and then, you can initialize the props with useState as below:

const [props, setProps] = useState<IProps>()

If you don't provide any value to the useState, it will initialize it automatically to the zero value of the corresponding type:

useState<string>()

is equivalent to

useState<string>("")

CodePudding user response:

I'm not sure that I understood part 2 of your question but I will try to answer

  1. the 0 in useState(0) => is an initial value you can put or Ignore it not a problem

  2. the second part is based on my understanding to it => that you want to set more than 1 prop so you can use multiple useState because in functional components it's allowed or you can use the useReducer to manage it.

But if you want to know how to access each prop in the component it's easy. the component is a function that gives you an argument called props that contains all your props like that

const component = (props) => {

  props // is an object that contains all your props
  
}

so you can access any props using props.propname

  • Related