Functional vs Class Components
# Class-based Components
In React Components were originally built by extending the React.Component
class. This gave them access to the state
property as well as a series of life cycle methods.
You will still find a fair number of React sites built with this syntax.
Note the import of the {Component}
object from react
, plus the constructor
function which receives the props
object.
import React, { Component } from 'react';
export default class MyApp extends Component {
constructor(props) {
super(props);
this.state = {}; //default value for state set here
}
someFunc = () => {
//a function attached to the MyApp component
//use the setState( ) method here to update state
};
componentDidMount() {
//lifecycle method that runs once component is ready
}
componentDidUpdate() {
//lifecycle method that runs once state has changed
}
render() {
//lifecycle method that will render the component
//by returning some JSX
//we can access this.state from here
return <div>MyApp</div>;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Functional Stateless Components
One of the big reasons that people used class-based components instead of the functional ones is the built-in access to the lifecycle and state.
This is why function-based components are called stateless
. They have no built-in way to access the value of state
or the lifecycle methods.
Then, in version 16.8, in early 2019, hooks and the Context API were added to React. These gave us a way to access state from any functional component at any depth, as well as the lifecycle events.
useState
gives us a way to access and update the value of state. useEffect
gives us a way to access the lifecycle events. The Context API
lets us pass state values from a root level component to a component nested deeply at any level without having to pass it through props.
import { useState, useEffect } from 'react';
export default function MyApp(props) {
//props passed directly into the function by React
//the return value from this function is the same as
//the return from the class-based render()
const [thing, setThing] = useState(true);
useEffect(() => {
//Similar to componentDidMount and componentDidUpdate
//function runs when there are changes to `thing`
}, [thing]);
}
2
3
4
5
6
7
8
9
10
11
12
13