React Notes

React Notes

JavaScript – React

Hooks

All react hooks begin with use.

When using react hook useState;

For Example: const [count, setCount] = useState(0);

count = 0 is the current state value, and setCount would be the function used to update the state

For Example setCount(count + 1); Increments count by 1. Every increment updates the state and causes a re-render of the component.

The setState can also take in a function

For Example: setCount(newCount => newCount + 1);

Where newCount represents the current state and the arrow function indicates how it will be updated;

Any React component written as a function is called a function component. React hooks like useState can only be used inside function components.

For Example;

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(prev => prev + 1)}>Increment</button>
    </div>
  );
}

useEffect happens outside of the life cycle component. Most common api get/put, local storage get/put.

Custom hooks are other hooks packaged together.

For example useFetch

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true; // Prevents state updates if the component unmounts

    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(url);
        if (!response.ok) throw new Error("Failed to fetch data");
        const result = await response.json();
        if (isMounted) {
          setData(result);
          setLoading(false);
        }
      } catch (err) {
        if (isMounted) {
          setError(err.message);
          setLoading(false);
        }
      }
    };

    fetchData();

    return () => {
      isMounted = false; // Cleanup function to avoid updating state on unmounted components
    };
  }, [url]); // Runs whenever the `url` changes

  return { data, loading, error };
}

Conditionals

Ternary Operator

function Greeting({ isLoggedIn }) {
  return <h1>{isLoggedIn ? "Welcome back!" : "Please sign in."}</h1>;
}

Logical AND (&&) for Shorter Conditions

function Notification({ hasNotifications }) {
  return (
    <div>
      <h1>Dashboard</h1>
      {hasNotifications && <p>You have new notifications!</p>}
    </div>
  );
}

Using Logical OR (||) for Default Values

function User({ name }) {
  return <h1>Welcome, {name || "Guest"}!</h1>;
}

Conditional Class Names (className with Ternary)

function Button({ isPrimary }) {
  return <button className={isPrimary ? "btn-primary" : "btn-secondary"}>Click Me</button>;
}

Conditional Prop Spreading

function ProfilePicture({ src }) {
  return <img {...(src && { src })} alt="Profile" />;
}

Only spreads the src prop if it’s truthy, preventing broken images.

View All Posts