Typescript+ReactJS: useState/useEffect vs component state interface/componentDidUpdate
Table of Contents
If you are using ReactJS with Typescript there are 2 alternative code styles: class based components and function based components.
useState
and useEffect
belong to function component style only.
For object-oriented style we use state interface
instead of useState
and componentDidUpdate
instead of useEffect
.
Example
Function based component
import React, {useState, useEffect} from "react";
interface MyFunctionComponentProps {
text:string;
x: number;
y: number;
}
const MyFunctionComponent: React.FC<MyFunctionComponentProps> = ({}) => {
const [items, setItems] = useState<number[]>([1,2,3]);
const [title, setTitle] = useState<string>("default title");
useEffect(() => {
// fires if entire state changed
});
useEffect(()=>{
// fires only if title changed
},[title]);
return (
<div className="title">{this.state.title}</div>
)
}
See also:
- useEffect https://reactjs.org/docs/hooks-reference.html#useeffect
- useState https://reactjs.org/docs/hooks-reference.html#usestate
- functional components and hooks general info https://reactjs.org/docs/hooks-overview.html
Class based component
import React, { Component } from "react";
from "react-konva";
export interface MyClassComponentProps {
text:string;
x: number;
y: number;
}
// this is useState hook alternative for class component
export interface MyClassComponentState {
items: number[];
title: string;
}
export default class MyClassComponent extends React.Component<MyClassComponentProps, MyClassComponentState> {
// default values for props
public static defaultProps = {
text: "",
x: 0,
y: 0,
}
public constructor(props) {
super(props);
// initial component state
this.state = {
items: [ 1, 2, 3 ]
};
}
// this is useEffect alternative for class component
public componentDidUpdate(prevProps, prevState, snapshot) {
// do something if props or state is changed
if( prevState.title !== this.state.title ) {
// do something if title is changed
}
}
public render() {
return (
<div className="title">{this.state.title}</div>
);
}
}
See also https://reactjs.org/docs/react-component.html
Pros and cons
As you can see, functional component code is much shorted and more clear.. in this particular case. Anyway, there is no reason to switch from classes to functions just because of useState/useEffect hooks.