Logo

dev-resources.site

for different kinds of informations.

My React Journey: Day 25

Published at
12/27/2024
Categories
webdev
react
mobile
deedoth
Author
ayoola_damilare_212d5bde0
Categories
4 categories in total
webdev
open
react
open
mobile
open
deedoth
open
Author
25 person written this
ayoola_damilare_212d5bde0
open
My React Journey: Day 25

Hooks - useState and useEffect

What Are React Hooks?
Hooks are special functions introduced in React v16.8 that allow functional components to use React features like state and lifecycle methods without writing class components.

1. useState Hook
The useState hook is used to add state to functional components.
It provides:

  • A state variable to store data.
  • A setter function to update the state. Syntax:
const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

Example:

import React, { useState } from 'react';

export default function MyComponent() {
  const [name, setName] = useState("Guest");
  const [age, setAge] = useState(0);

  const updateName = () => setName("Damilare");
  const updateAge = () => setAge(age + 2);

  return (
    <div>
      <p>Name: {name}</p>
      <button onClick={updateName}>Update Name</button>

      <p>Age: {age}</p>
      <button onClick={updateAge}>Increase Age</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

2. useEffect Hook
The useEffect hook allows you to perform side effects in functional components. Examples include:

  • Fetching data from an API.
  • Subscribing to events.
  • Directly updating the DOM (e.g., changing document.title). Syntax:
useEffect(callback, [dependencies]);
Enter fullscreen mode Exit fullscreen mode
  • callback: The function to execute.
  • [dependencies]: Array of values that the effect depends on.

Behavior Based on Dependencies:

  1. useEffect(() => { ... }); Runs after every re-render of the component.
  2. useEffect(() => { ... }, []); Runs only on mount (like componentDidMount).
  3. useEffect(() => { ... }, [value]); Runs on mount and whenever value changes.

Example:

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

export default function UseEffectHook() {
  const [count, setCount] = useState(0);
  const [color, setColor] = useState("green");

  // Runs on mount and whenever count or color changes
  useEffect(() => {
    document.title = `Count: ${count} - Color: ${color}`;
  }, [count, color]);

  const incrementCount = () => setCount(count + 1);
  const decrementCount = () => setCount(count - 1);
  const toggleColor = () => setColor(color === "green" ? "red" : "green");

  return (
    <>
      <p style={{ color }}>{`Count: ${count}`}</p>
      <button onClick={incrementCount}>Add</button>
      <button onClick={decrementCount}>Subtract</button>
      <button onClick={toggleColor}>Change Color</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Use Cases of useEffect:

  1. Event Listeners: Add/remove listeners (e.g., window.addEventListener).
  2. Fetching Data: Fetch API data when a component mounts or state changes.
  3. DOM Updates: Update document.title or other DOM properties.
  4. Cleanups: Handle cleanup tasks like unsubscribing from listeners.

Cleanup Example:

useEffect(() => {
  const timer = setInterval(() => console.log('Running...'), 1000);

  return () => {
    clearInterval(timer); // Cleanup on unmount
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • State in Functional Components: Use useState for state variables.
  • Side Effects: Use useEffect for anything that interacts with the outside world or reacts to changes in state/props.
  • Dependency Array: Always specify the dependency array to avoid unnecessary renders or infinite loops.
  • Cleanups: Always clean up subscriptions, intervals, or listeners in useEffect. With useState and useEffect, building React applications becomes easier and more intuitive.

Day after day.
Understanding upon understanding.

Featured ones: