Navigating the Waters of React Hooks

Navigating the Waters of React Hooks

1*IxViyGJCI1Y_474QKLr3WQ Navigating the Waters of React Hooks

Ahoy there, sailors of the digital realm! When setting sail in the expansive ocean of React development, one might often hear tales of the mysterious and powerful Hooks. With their prowess, they’ve revolutionized the way components function (pun intended). Join us on this voyage as we explore and demystify these Hooks.

What are Hooks?

Hooks are functions that allow you to “hook into” React state and lifecycle features directly from function components. They were introduced to solve a variety of issues and allow for more intuitive state management and side-effect handling in function components.

Setting Sail with useState

Perhaps the most commonly used Hook, useState grants us the capability to add state management to our function components.

import React, { useState } from 'react';

function ShipCounter() {
  const [shipCount, setShipCount] = useState(0);
  return (
    <div>
      <p>Ships sighted: {shipCount}</p>
      <button onClick={() => setShipCount(shipCount + 1)}>Add Ship</button>
    </div>
  );
}

In this simple example, we’ve created a ship counter. We initialize our state with a value of 0, and each time the button is pressed, the count increases.

Tackling Side Effects with useEffect

Side effects (data fetching, subscriptions, manual DOM manipulations) are indispensable in modern applications. useEffect allows us to perform side effects directly from our function components.

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

function ShipLog() {
  const [logs, setLogs] = useState([]);
  useEffect(() => {
    // Fetching our ship logs from an API
    fetch('/api/shipLogs')
      .then(response => response.json())
      .then(data => setLogs(data));
  }, []); // The empty array means this useEffect runs once when the component mounts
  return (
    <ul>
      {logs.map(log => (
        <li key={log.id}>{log.entry}</li>
      ))}
    </ul>
  );

The useEffect here fetches ship logs when our ShipLog component first mounts.

Charting Dependencies with useEffect

The dependency array (the last argument in useEffect) can be a bit tricky. It indicates when the effect should re-run. If a value in the dependency array changes between renders, the effect will run again.

function ShipDetails({ shipId }) {
  const [ship, setShip] = useState(null);

useEffect(() => {
    fetch(`/api/ships/${shipId}`)
      .then(response => response.json())
      .then(data => setShip(data));
  }, [shipId]); // Re-run the effect if shipId changes
}

In the above component, whenever shipId changes, the useEffect fetches new ship details.

Steering Custom Hooks

Custom Hooks allow you to extract component logic into reusable functions. Let’s create a custom Hook to fetch ship details:

function useShipDetails(shipId) {
  const [ship, setShip] = useState(null);

useEffect(() => {
    fetch(`/api/ships/${shipId}`)
      .then(response => response.json())
      .then(data => setShip(data));
  }, [shipId]);
  return ship;
}
// Usage in a component:
function ShipComponent({ shipId }) {
  const ship = useShipDetails(shipId);
  return <div>{ship?.name}</div>;
}

We’ve taken the fetching logic from ShipDetails and encapsulated it in useShipDetails, making it reusable.

Anchoring Down

React Hooks provide a world of possibilities, turning our functional components into powerhouses. As with any voyage, the waters might seem challenging initially, but with experience, the journey becomes thrilling.

For more such adventures in the world of code and to set sail with us, anchor your ship to our dock: www.thecodearmada.com

Founder & CEO

Lyron Foster is a Prolific Multinational Serial Entrepreneur, Blogger, Author, IT Trainer, Polyglot Coder, Real Estate Investor and Technologist.

Related Posts

Write a comment