< Back to Coding, React

Basic React Function Component

This is a copy of this post, but using a function component and hooks.

import React, { useState, useEffect } from 'react';

import "./ConditionalClass.css"

function FunctionComponent(props) {

  const [con1, toggleCon1] = useState(false);
  const [con2, toggleCon2] = useState(false);

  useEffect(() => {
    //replaces componentDidUpdate() in class components. happens after render

    return function cleanup() {
      console.log("cleanup"); //similar to componentWillUnmount()

  }, []) // <-- add [] to change it to act like componentDidMount(). By declaring no dependencies, there's nothing to check to see if it changed, so it never reruns

  return (
      <button onClick={() => toggleCon1(!con1)}>toggle 1</button>
      <button onClick={() => toggleCon2(!con2)}>toggle 2</button>

      <div className={`defaultClass ${con1 ? "con1" : ""} ${con2 ? "con2" : ""

export default FunctionComponent;

Leave a Reply

Your email address will not be published. Required fields are marked *