Title Image

January 29, 2021

Hola. 👋🏾

A constructor in a React component is used for 1 of 2 reasons:

  • When setting up local state
  • When binding a value

The constructor isn't mandatory, but React function components have ways of still allowing us to perform both of the above actions if we need to. I've commented in the example below how we were using the constructor for two reasons.

1import React, { Component } from 'react'
2import { View } from 'react-native'
3
4class Form extends Component {
5 constructor(props) {
6 super(props)
7 // setting up local state
8 this.state = {
9 name: '',
10 email: '',
11 }
12
13 // binding ref's
14 this.nameRef = React.createRef()
15 this.emailRef = React.createRef()
16 }
17
18 render() {
19 return <View></View>
20 }
21}
22
23export default Form

Function components allow us to use React Hooks. Since we've created our component with fat arrow syntax, we also don't need to reference "this" anymore because our variables are already bound. 💯

Instead of having a single object that holds our local state, we will use the "useState" React hook. The setup is pretty straightforward. const [<stateName>, <setStateName>] = useState(<initial state value>). While naming your "setter" the same as the actual state variable name isn't required, I find it easier to reason about what's going on.

Next, we replace "React.createRef". There's a "createRef" hook, but we'll be using the "useRef" hook instead. The difference between the two is that "createRef" will create a new ref every time the component renders. "useRef", as its name suggests, uses the same ref every time the component renders. In short, "useRef" is more useful. 😄

1import React, { useRef, useState } from 'react'
2import { View } from 'react-native'
3
4const Form = () => {
5 // setting up local state
6 const [name, setName] = useState('')
7 const [email, setEmail] = useState('')
8
9 // binding ref's
10 const nameRef = useRef()
11 const emailRef = useRef()
12
13 return <View></View>
14}
15
16export default Form

See you next time. 🙃