React Hooks: useEffect

In react hooks we can utilize useEffect hook to add codes that can “observe” the other variables or codes and run the codes inside its callback function.

An example here

import React from "react";

export default function App() {
  const [buttonToggle, setButtonToggle] = React.useState(false);

  React.useEffect(() => {
    alert("Toggled");
  }, [buttonToggle]);

  return (
    <div className="App">
      <button
        style={{ backgroundColor: buttonToggle ? "transparent" : "yellow" }}
        onClick={() => {
          setButtonToggle(!buttonToggle);
        }}
      >
        Toggle
      </button>
    </div>
  );
}

The useEffect here “observe” the changes in buttonToggle variable and when the variable value change it will display an alert in browser window.

Reference:

  • https://reactjs.org/docs/hooks-effect.html

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.