February 05, 2021

React Class to Function Pt. 4

Title Image

Hola. 👋🏾

Lifecycle methods are a pretty big deal in class components. There are so many because each one is called at a different point in the life of the component. They're basically broken into 3 categories though: before the component mounts, after the component mounts and when the component is going to unmount.

The "render" method is the most used lifecycle method and the only required one in every class component. I'd assume that componentDidMount is second to render. It's where you put your code that you'd like to be set when the component has mounted. In our case, we were setting up a keyboard listener. We only want the app to pay attention to this listener while our component is on screen though, so we remove the listener in the "componentWillUnmount" method.

1import React, { Component } from 'react'
2import { View } from 'react-native'
3
4class Form extends Component {
5 componentDidMount() {
6 this.keyboardDidHide = Keyboard.addListener(
7 'keyboardDidHide',
8 this._keyboardDidHide
9 )
10 }
11
12 componentWillUnmount() {
13 this.keyboardDidHide.remove()
14 }
15
16 _keyboardDidHide = () => this.props.scrollDown()
17
18 render() {
19 return <View></View>
20 }
21}
22
23export default Form

In our functional component, the "componentDidMount" and "componentWillUnmount" methods can be written using the same hook: "useEffect". You can have multiple "useEffect's" in a single component and they also can take a value in the square brackets at the end. For our conversion, we don't need either of those things. We move whatever was in the "componentDidMount" into the body of the "useEffect". Then we move whatever was in the "componentWillUnmount" into a return function at the end of the "useEffect".

1import React, { useEffect } from 'react'
2import { View } from 'react-native'
3
4const Form = ({ scrollDown }) => {
5 useEffect(() => {
6 const keyboardDidHide = Keyboard.addListener(
7 'keyboardDidHide',
8 _keyboardDidHide
9 )
10
11 return () => {
12 keyboardDidHide.remove()
13 }
14 }, [])
15
16 const _keyboardDidHide = () => scrollDown()
17
18 return <View></View>
19}
20
21export default Form

See you next time. 🙃