🎯4 Rules to remember before using React Hooks

🎯4 Rules to remember before using React Hooks

Table of contents

No heading

No headings in the article.

✅You should only call Hooks from a React Functional Component.

✅You should only call Hooks at the Top level.

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

function App() {
  const [name, setName] = useState("John");

  const changeName = () => (name == "John"? setName("Doe") : setName("John"))

  return (
    <div>
      <h1>{name}</h1>
      <button onClick={changeName}>Change Name</button>
    </div>
  )
}

export default App

✅You can use multiple state or effect hooks in a single component.

✅You should call Multiple Hooks calls in the same sequence.

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

function App() {
  const [name, setName] = useState("John")
  const [age, setAge] = useState(25)

const changeName = () => (name == "John" ? setName("Doe") : setName("John"))

  useEffect(() => {
    if (name == "John") {
      setName("John Doe")
    }
  }, [])

  return (
    <div>
      <h1>{name}</h1>
      <h2>{age}</h2>
      <button onClick={changeName}>Change Name</button>
    </div>
  );
}

export default App

❌ Never declare any hook inside if block, loop, or any function. ❌

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

function App() {
  if (true) {
  // Never do this  
  const [name, setName] = useState("John"); 
  }
  const [age, setAge] = useState(25);

  const changeName = () => (name == "John"? setName("Doe") : setName("John"))

  return (
    <div>
      <h1>{name}</h1>
      <button onClick={changeName}>Change Name</button>
    </div>
  )
}

export default App

🚀Use the power of React Hooks!!!

💡Happy Learning!