DEV Community 👩‍💻👨‍💻

Cover image for Hooks in React
suraj more
suraj more

Posted on

Hooks in React

Hooks are a new feature introduced in React 16.8 and available in later versions. We can use state and other features of react by using hooks. React has two ways of creating component, one is using class and other is using function.

using class to generate component needs to add react boiler-plate code because of that using function for generating component is introduced. to use state like features of react in later way hooks are useful.

There are certain hooks that react provide us. useState, useEffect, useRef and useReducer. but we can create custom hooks as per our requirements.

useState:

as name suggests it used to handle state of component. It helps to manage state between component re-renders.

lets look at example below,
we have one button "Click Me", on clicking that button text should be changed to "title changed"

export default function App() {
  let title = "Initial header";
  const handleClick = () => {
    title = "title changed";
    console.log(title);
  }
  return (
    <div className="App">
      <h1>{title}</h1>
      <button onClick={handleClick}>Click Me</button>

    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

without_usestate

as we can see, when button is clicked the title value is changed in console, but on browser it shows old value, to update value component needs to re-render and between that rendering process we also need to maintain updated state. This thing can be achieved using useState

import { useState } from "react";

export default function App() {
  const [title, setTitle] = useState("Initial header");
  const handleClick = () => {
    setTitle("title changed");
  };
  return (
    <div className="App">
      <h1>{title}</h1>
      <button onClick={handleClick}>Click Me</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

with_usestate

useEffect:

useEffect hook is used to handle activities when component renders . There is some syntax variation is used to customize useEffect.

//executes at component's initial render
  useEffect(()=> {

  }, []);

//executes at component's state title is changed.
  useEffect(()=> {

  }, title);

//executes at component's renders
  useEffect(()=> {

  });
Enter fullscreen mode Exit fullscreen mode

useEffect

Top comments (0)

🌚 Life is too short to browse without dark mode