React Hooks You Can Use in Every Project – Explained with Examples

React hooks, introduced in version 16.8, have revolutionized the way we write components. By allowing us to use state and other React features without writing a class, hooks make code more concise, composable, and reusable across projects. In this guide, we‘ll explore some of the most essential React hooks that you‘ll likely reach for in every project, along with practical examples of how to use them.

The useState Hook

The useState hook is the foundation of state management in function components. It allows us to declare state variables and provides a way to update them. Here‘s the basic syntax:

const [state, setState] = useState(initialState);

The useState hook takes an initial state value as an argument and returns an array containing the current state and a function to update it. Here‘s an example of using useState to manage a counter:

import React, { useState } from ‘react‘;

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In this example, we declare a count state variable with an initial value of 0. We then use the setCount function to increment the count whenever the button is clicked.

The useEffect Hook

The useEffect hook allows us to perform side effects in function components. Side effects include things like fetching data, subscribing to event listeners, or manually changing the DOM. The useEffect hook takes two arguments: a callback function and an optional array of dependencies. Here‘s an example of using useEffect to fetch data from an API:

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

function DataFetcher() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch(‘https://api.example.com/data‘)
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <ul>
      {data.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

In this example, we use useEffect to fetch data from an API when the component mounts. We provide an empty array [] as the second argument to ensure that the effect only runs once. Once the data is fetched, we update the data state variable using setData.

The useContext Hook

The useContext hook allows us to access the value of a Context object in a function component. Context provides a way to share values between components without explicitly passing props down the tree. Here‘s an example of using useContext to share a theme value between components:

import React, { useContext } from ‘react‘;

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

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme === ‘dark‘ ? ‘black‘ : ‘white‘, color: theme === ‘dark‘ ? ‘white‘ : ‘black‘ }}>
      Themed Button
    </button>
  );
}

In this example, we create a ThemeContext using React.createContext and provide a default value of ‘light‘. We then wrap the Toolbar component with a ThemeContext.Provider and set the value to ‘dark‘. In the ThemedButton component, we use the useContext hook to access the current theme value and conditionally style the button based on the theme.

The useRef Hook

The useRef hook allows us to create a mutable reference that persists across component re-renders. It‘s commonly used for accessing DOM elements or storing values that don‘t require the component to re-render when they change. Here‘s an example of using useRef to access an input element:

import React, { useRef } from ‘react‘;

function InputFocus() {
  const inputRef = useRef();

  const handleClick = () => {
    inputRef.current.focus();
  };

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

In this example, we create a ref using useRef and assign it to the input element using the ref attribute. We then define a handleClick function that accesses the input element via inputRef.current and calls its focus method. When the button is clicked, the input will receive focus.

The useMemo and useCallback Hooks

The useMemo and useCallback hooks are used for performance optimization by memoizing expensive computations or callback functions. useMemo memoizes the result of a computation, while useCallback memoizes the callback function itself. Here‘s an example of using useMemo to memoize an expensive computation:

import React, { useMemo } from ‘react‘;

function ExpensiveComponent({ data }) {
  const expensiveResult = useMemo(() => {
    // Perform expensive computation here
    return computeExpensiveResult(data);
  }, [data]);

  return <div>{expensiveResult}</div>;
}

In this example, we use useMemo to memoize the result of an expensive computation. The computation will only be re-run if the data dependency changes. This can help avoid unnecessary re-computations on each render.

Custom Hooks from Libraries

In addition to the built-in React hooks, there are many useful custom hooks available from libraries like react-use. Here are a few examples:

  • useMedia: A hook for handling media queries in React components.
    
    import { useMedia } from ‘react-use‘;

function MyComponent() {
const isWide = useMedia(‘(min-width: 768px)‘);

return (

{isWide ? (

) : (

)}

);
}
“`

  • useCopyToClipboard: A hook for copying text to the clipboard.
    
    import { useCopyToClipboard } from ‘react-use‘;

function MyComponent() {
const [text, setText] = useState(‘Hello, World!‘);
const [state, copyToClipboard] = useCopyToClipboard();

return (

setText(e.target.value)} />

{state.error ? (

Unable to copy value: {state.error.message}

) : (
state.value &&

Copied {state.value}

)}

);
}
“`

  • useLocalStorage and useSessionStorage: Hooks for using localStorage and sessionStorage in React components.
    
    import { useLocalStorage, useSessionStorage } from ‘react-use‘;

function MyComponent() {
const [name, setName] = useLocalStorage(‘name‘, ‘John‘);
const [count, setCount] = useSessionStorage(‘count‘, 0);

return (

setName(e.target.value)}
/>

Name: {name}

Count: {count}

);
}
“`

These are just a few examples of the many custom hooks available. When building your own projects, consider exploring libraries like react-use to find hooks that can save you time and effort.

Conclusion

React hooks are a powerful tool for creating reusable and composable code in your projects. By leveraging hooks like useState, useEffect, useContext, useRef, useMemo, and useCallback, you can manage state, handle side effects, share values between components, access DOM elements, and optimize performance. Additionally, custom hooks from libraries like react-use can provide even more functionality and convenience.

As you work on your own projects, consider how you can utilize these hooks to write cleaner, more efficient code. Don‘t be afraid to experiment and create your own custom hooks as well. With a solid understanding of React hooks, you‘ll be well-equipped to tackle any project that comes your way.

For more information on React hooks, check out the official documentation at reactjs.org and explore the react-use library at github.com/streamich/react-use. Happy coding!

Similar Posts