7 Useful React Hooks You Should Know

React JS

Discover the top 7 React hooks that can simplify your development process and enhance your React applications in 2024. Learn how to use these hooks with practical examples.


NGNishan Giri
2024-05-23
7 Useful React Hooks You Should Know

React hooks have transformed the way we write React components, making it easier to manage state, side effects, and other functionalities. Here are 7 useful React hooks that every developer should know.

1. useState

The useState hook is used to manage state in a functional component. It returns an array with two elements: the current state and a function to update it.

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>
  );
}
 
export default Counter;

2. useEffect

The useEffect hook lets you perform side effects in function components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes.

import React, { useState, useEffect } from 'react';
 
function Timer() {
  const [seconds, setSeconds] = useState(0);
 
  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prevSeconds => prevSeconds + 1);
    }, 1000);
 
    return () => clearInterval(interval);
  }, []);
 
  return (
    <div>
      <p>Seconds elapsed: {seconds}</p>
    </div>
  );
}
 
export default Timer;

3. useContext

The useContext hook lets you subscribe to React context without introducing nested functions in your component.

import React, { useContext } from 'react';
 
const ThemeContext = React.createContext('light');
 
function ThemedButton() {
  const theme = useContext(ThemeContext);
 
  return (
    <button style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
      I am styled by theme context!
    </button>
  );
}
 
export default ThemedButton;

4. useReducer

The useReducer hook is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

import React, { useReducer } from 'react';
 
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}
 
function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
 
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>
        +
      </button>
      <button onClick={() => dispatch({ type: 'decrement' })}>
        -
      </button>
    </div>
  );
}
 
export default Counter;

5. useRef

The useRef hook returns a mutable ref object whose .current property is initialized to the passed argument. This object persists for the full lifetime of the component.

import React, { useRef } from 'react';
 
function TextInputWithFocusButton() {
  const inputEl = useRef(null);
 
  const onButtonClick = () => {
    inputEl.current.focus();
  };
 
  return (
    <div>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </div>
  );
}
 
export default TextInputWithFocusButton;

6. useMemo

The useMemo hook returns a memoized value. Pass a "create" function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed.

import React, { useMemo } from 'react';
 
function ExpensiveCalculationComponent({ num }) {
  const expensiveCalculation = useMemo(() => {
    return num ** 2;
  }, [num]);
 
  return <div>Expensive Calculation Result: {expensiveCalculation}</div>;
}
 
export default ExpensiveCalculationComponent;

7. useCallback

The useCallback hook returns a memoized callback. Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.

import React, { useState, useCallback } from 'react';
 
function IncrementButton() {
  const [count, setCount] = useState(0);
 
  const increment = useCallback(() => {
    setCount(count + 1);
  }, [count]);
 
  return <button onClick={increment}>Increment: {count}</button>;
}
 
export default IncrementButton;

Conclusion

These 7 React hooks can greatly simplify your code and make your components more efficient and easier to understand. By mastering these hooks, you can take full advantage of React's powerful features and improve your development workflow. Try incorporating these hooks into your projects and see how they can enhance your React applications in 2024!


Happy Coding! 😊