Hooked on React: Exploring useRef, useState, and useEffect

Hooked on React: Exploring useRef, useState, and useEffect

Introduction

Introduced in React 16.8, React Hooks revolutionized how developers use React concepts like props, state, context, refs, and more. Before the introduction of React Hooks, handling and controlling data within a software application could be complex, leading to code with minimal reusability. DRY who?

React Hooks introduced the concept of simple, but powerful, reusable functions. In addition to moving away from the usage of class components, Hooks have enabled the use of functional components for state management, improved the organization and readability of code, and allowed for better handling of side effects. Furthermore, for new React users like myself, using Hooks has been a more straightforward and intuitive way of building code.

In this article, we'll wade into the waters of React Hooks and explore some of the more commonly used Hooks: useRef, useState, and useEffect.

The useState Hook

The "useState" Hook is one of the most used Hooks in React. State allows a component to update and retain information given by the user or by the developer. For example, a user may enter their username on the server and the state would capture the value that was given. When a new user adds their information, React will re-render the component, and the new data will be stored. See below for the general syntax.

const [state, useState] = useState(initialState);
  • "state": current state value that can be read and updated

  • "setState": a function that updates the state

  • "initialState": default and given value of the state

The "useState" Hook takes in two arguments, the initial state value and a function to update the state. A best practice is to use a naming convention of state and useState for the two inputs. See below for a simple example of how to useState to capture and update a counter.

Do I have you hooked yet? If not, keep reading to find out more!

The useEffect Hook

The "useEffect" Hook is another important tool that allows developers to manage side effects in components. This Hook lets the developer coordinate a component's behavior with an external system or perform tasks in response to specific conditions or changes. The "useEffect" Hook can be used for data fetching, conditional functions, and triggering side effects based on external changes. See below for the general syntax of useEffect.

const useEffect(() => {
...
},[dependencies]);
  • "useEffect(() => {...}, [dependencies])": main function that receives a function and an array of dependencies

The function within useEffect would be the code you wish to execute either when the component first mounts or if a dependency changes. Having a dependency is optional and depends on whether you want the function to be triggered by an external factor. If there is no dependency, then you can use an empty array "[]" and the effect will only run just once when the component mounts. For example, below, you'll see how useEffect and useState can be used to fetch and store data, dependent on changes in a variable like "test."

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

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

  //function that fetches the data and stores it in the data state
  const fetchData = () => {
    fetch('url')
    .then(r => r.json())
    .then(setData)
    .catch(err => alert(err))
   }  
//triggered by some variable test
useEffect(() => {
    fetchData();
  }, [test]);

  return (
    <div>
      {content}
    </div>
  );
}

Ready to get "hooked" on another React tool?

The useRef Hook

The "useRef" Hook allows a developer to: directly manage and control data without triggering a page reload and retain information between renders. The "useRef" hook returns a ref object that has an initial value set by the user. Unlike "useState" which triggers a re-render, changing a ref will not cause the page to re-render. This is a great tool to use when interacting with the DOM and when storing data that is outside of the typical render/re-render React component lifecycle. See below for an example of the general syntax used for this hook.

const ref = useRef(initialValue);
console.log(ref.current) //would return "initialValue"
//mutating the initial value
ref.current = newValue;

To access and mutate the "ref", you would use "ref.current." This will either provide you with the initial value you set or you could set it to a new value. As mentioned before, changing the value of "ref" will not trigger a re-render. See below for an example of how you could store and interact with a DOM element using "useRef."

Conclusion

The React Hooks "useState", "useEffect", and "useRef" are powerful tools a developer can use to build more interactive and dynamic applications with greater ease and efficiency. With these Hooks, developers can manipulate, store, and access data in a more intuitive and user-friendly way. As we delve deeper into the world of React, we will use these foundational tools again and again.