DEV Community

Cover image for React Hooks Explained: useState, useEffect, useRef & useNavigate
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

React Hooks Explained: useState, useEffect, useRef & useNavigate

useState() – Store and Update Data
useState() is used to store data inside a React component and update it.

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  return (
    <>
      <h2>{count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Click Me
      </button>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

useEffect() – Perform Side Effects
useEffect() is used to perform actions like fetching API data and updating the page title.

import { useEffect } from "react";

function App() {

  useEffect(() => {
    console.log("Welcome to React!");
  }, []);

  return <h2>Hello World</h2>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

useRef() – Access HTML Elements
useRef() is used to access HTML elements directly and store values without causing a re-render.

import { useRef } from "react";

function App() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>
        Focus Input
      </button>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

useNavigate() – Move Between Pages
useNavigate() is used to navigate from one page to another in React Router.

import { useNavigate } from "react-router-dom";

function Home() {
  const navigate = useNavigate();

  return (
    <button onClick={() => navigate("/about")}>
      Go to About Page
    </button>
  );
}

export default Home;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)