Exploring the Power of Basic React Hooks

In the ever-evolving landscape of front-end development, React has established itself as a powerhouse for building dynamic user interfaces. One of the most significant additions to React in recent years has been the introduction of hooks, which revolutionized how developers manage state and side effects in functional components. In this blog post, we’ll delve into some of the most commonly used basic React hooks and explore their utility with code examples.

useState()

The useState() hook is perhaps the most fundamental hook in React. It allows functional components to hold and update state. Here’s a simple example:

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
};

export default Counter;

Results in the following:

useEffect()

The useEffect() hook enables performing side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM. Here’s how you can use it:

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

const DataFetcher = () => {
  const [data, setData] = useState(null);
  const fetchData = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/users");
    const result = await response.json();
    setData(result);
  };
  useEffect(() => {
    fetchData();
  }, []); // Empty dependency array means this effect runs only once

  return (
    <div>
      <button onClick={() => {
        fetchData();
      }}>Refresh Users</button>
      <h2>List of Users</h2>
      {data ? (
        <ul>
          {data.map((item, index) => (
            <li key={index}>{item.name}</li>
          ))}
        </ul>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};

export default DataFetcher;

Results in the following:

useContext()

The useContext() hook provides a way to consume values from React context without nesting. Here’s a simple example:

import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

const ThemedComponent = () => {
  const theme = useContext(ThemeContext);

  return <div>Current theme: {theme}</div>;
};

export default ThemedComponent;

Results in the following:

useRef()

The useRef() hook returns a mutable ref object whose .current property is initialized to the passed argument. It’s commonly used for accessing DOM nodes or persisting values between renders without causing re-renders. Here’s an example:

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

const FocusInput = () => {
  const inputRef = useRef(null);
  const [stuff, setStuff] = useState('')
  const focusInput = () => {
    if (inputRef.current) {
      inputRef.current.focus();
      setStuff(inputRef.current.value);
    }
  };

  return (
    <div>
      <input type="text" placeholder="username" />
      <input type="text" placeholder="password" />
      <input ref={inputRef} type="text" placeholder="shortname"/>
      <p>{`${stuff}`}</p>
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
};

export default FocusInput;

Results in the following: