React state comparison: class vs function


YouTube video:

CodeSandbox demo:

Class

Rendering initial state:

import React, { Component } from 'react';

export default class Klass extends Component {
  state = {
    count: 0,
  };
  render() {
    return <button>{this.state.count}</button>;
  }
}

Updating state:

import React, { Component } from 'react';

export default class Klass extends Component {
  state = {
    count: 0,
  };
  handleClick = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };
  render() {
    return <button onClick={this.handleClick}>{this.state.count}</button>;
  }
}

Class state property must be an object since setState takes an object of state variables to update.

Function

Rendering initial state:

import React, { useState } from 'react';

export default function Funktion() {
  const initialState = {
    count: 0,
  };
  const [state] = useState(initialState);
  return <button>{state.count}</button>;
}

Updating state:

import React, { useState } from 'react';

export default function Funktion() {
  const initialState = {
    count: 0,
  };
  const [state, setState] = useState(initialState);
  function handleClick() {
    setState({
      count: state.count + 1,
    });
  }
  return <button onClick={handleClick}>{state.count}</button>;
}

There can be multiple useState hooks in a function.

The initial state passed to useState doesn’t have to be an object:

import React, { useState } from 'react';

export default function Funktion() {
  const initialCount = {
    count: 0,
  };
  const [count, setCount] = useState(initialCount);
  function handleClick() {
    setCount(count + 1);
  }
  return <button onClick={handleClick}>{count}</button>;
}

Resources



Please support this site and join our Discord!