paint-brush
A Beginner’s Guide to React Hooks and How to Use Themby@deewyne
2,673 reads
2,673 reads

A Beginner’s Guide to React Hooks and How to Use Them

by Daniel YerimahJanuary 23rd, 2023
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

React Hooks are a new feature in React 16.8 that allows you to use state and other React features without writing a class. This makes it easy to share stateful logic between components and helps make your code more reusable. Hooks also allow you to split your code into smaller, reusable pieces, which can make it easier to manage and test.
featured image - A Beginner’s Guide to React Hooks and How to Use Them
Daniel Yerimah HackerNoon profile picture

What are React Hooks and why are they useful?

React Hooks are a new feature in React 16.8 that allows you to use state and other React features without writing a class. This makes it easy to share stateful logic between components and helps make your code more reusable and easier to understand. Hooks are also useful because they allow you to split your code into smaller, reusable pieces, which can make it easier to manage and test.


Differences between React Hooks and class-based components

Some key differences between React Hooks and class-based components include:


  1. Hooks allow you to use state and other React features in function components: Before the introduction of Hooks, only class-based components could have state and use other React features such as lifecycle methods. With Hooks, you can add state and other React features to function components, making them more versatile and reusable.


  2. Hooks make your code more concise and readable: Class-based components can become long and complex, especially if you have to manage a lot of state or lifecycle methods. With Hooks, you can use simple, focused functions to handle individual pieces of state and logic, which can make your code more readable and easier to understand.


  3. Hooks allow you to reuse stateful logic: With Hooks, you can extract stateful logic from a component and share it across multiple components, making your code more reusable and easier to maintain. This is especially useful if you have a complex component with a lot of stateful logic, and want to extract some of that logic into reusable functions.


Basic React Hooks

useState()

The useState hook is a function in React that allows you to add a state to functional components. State is a collection of values that determine a component's behavior and render information to the user. The useState hook takes a single argument, which is the initial state and returns an array with two elements.


The first element is the current value of the state, and the second element is a function that you can use to update the state. Here's an example of how you might use the useState hook in a functional component:


import React, { useState } from 'react';

const myComponent = () => {
  // Declare a new state variable, which we'll call "count"
  // The initial value of count is 0
  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, the useState hook is used to add a piece of state called count to the MyComponent functional component. The initial value of count is 0, and the setCount function is used to update the value of count when the button is clicked. Every time the button is clicked, the value of count will be incremented by 1 and the component will re-render with the updated value.


useEffect()

useEffect is a hook in React that allows you to perform side effects in function components. This can include things like setting up subscriptions, modifying the DOM, and interacting with external APIs.

It is called inside the component and will run every time the component renders.


Here is an example of how to use it:


import React, { useEffect } from 'react';

const MyComponent = () => {
  useEffect(() => {
    // Perform some side effect, like subscribing to a data source
    const subscription = someDataSource.subscribe(data => {
      // Update state with the data from the subscription
      setState({ data });
    });

    // Clean up the subscription when the component unmounts
    return () => subscription.unsubscribe();
  });

  // Render the component
  return (
    <div>
      {/* Use the data from the state in the render method */}
      Data: {state.data}
    </div>
  );
}


In this example, the useEffect hook is used to set up a subscription to a data source and update the component's state with the data from the subscription. It also includes a cleanup function that will be called when the component unmounts, to ensure that the subscription is properly cleaned up and doesn't cause memory leaks.


useContext()

useContext is a hook in React that allows you to access the value of a context from within a function component. Context provides a way to pass data through the component tree without having to pass props down manually at every level.


Here is an example of how to use useContext:


import React, { useContext } from 'react';

// Create a context with a default value
const MyContext = React.createContext('defaultValue');

function MyComponent() {
  // Use the useContext hook to access the value of the context
  const value = useContext(MyContext);

  return (
    <div>
      {/* Use the value from the context in the render method */}
      Value from context: {value}
    </div>
  );
}


In this example, the useContext hook is used to access the value of the MyContext context within the MyComponent function component. The value of the context can then be used in the render method.


It is important to note that the value of the context will only be updated in the components where the context is used if the provider that supplies the value of the context is updated. This means that any changes to the value of the context will only be reflected in the components that use the context if the provider is re-rendered with the updated value.


Advanced React Hooks

useReducer()

useReducer is a hook in React that is used for managing state in a React application. It is similar to the useState hook, but it allows you to manage more complex state objects and provides a way to handle actions in a reducer function.


Here is an example of how useReducer might be used in a React component:


import React, { useReducer } from 'react';


const initialState = { count: 0 };
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, initialState);
  return (
  <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
    </>
  );
}


In this example, the useReducer hook is used to manage the state of a simple counter component. The hook is called with the reducer function and the initial state, and it returns the current state and a dispatch function that can be used to dispatch actions to the reducer. In this case, the component has two buttons that dispatch 'increment' and 'decrement' actions to the reducer, which updates the count in the state accordingly.


useMemo()

useMemo is a hook in React that allows you to optimize the performance of a component by memoizing its result. It takes a function and an array of dependencies as arguments, and returns the memoized result of the function.


Memoization is simply an optimization technique used to increase an application's speed and efficiency. it does this by storing the results of computation and returning the cached result when the same inputs occur again.


The array of dependencies tells React when to re-run the memoized function. Every time one of the dependencies in the array changes, the memoized function will be re-run. This can be useful for optimizing performance in large or complex components, where re-computing the result of a function every time the component renders can be costly.


useRef()

In React, the useRef hook is used to create a reference to a DOM element or a React component instance. This reference can then be used to access the properties of the element, such as its value or checked state, or to call functions on the element, such as focus or click.


Here is an example of how useRef can be used to focus an input element when a button is clicked:


import { useRef } from 'react';

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

  function handleClick() {
    // Use the `current` property of the ref to access the DOM element
    inputRef.current.focus();
  }

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


In this example, the inputRef variable is created by calling useRef and passing null as the initial value for the ref. This ref is then attached to the input element by setting the ref attribute to inputRef.


When the handleClick function is called, it uses the current property inputRef to access the input element and calls its focus method, which moves the focus to the input element.


Note that useRef should not be used to store state in your component. Instead, use the useState hook for that purpose. useRef is intended for storing references to non-React values, such as DOM elements.

Common use cases for React Hooks

  • Managing state in simple and complex components
  • Performing side effects such as API calls and subscriptions
  • Optimizing performance with memoization
  • Creating references to elements for use in animations and interactions

Conclusion

In conclusion, react hooks offer several benefits over traditional class-based components. Such as simplicity, reusability, composability (that is the ability to combine multiple pieces of logic into a single function), and improved performance.


I would advise you to familiarize yourself with the basics of React Hooks and try to apply them in your next project.