Day 39-Custom Hooks,Refs and more state - Lesson 1

Hello and welcome to day 39 of my challenge!πŸ’•πŸ’ͺ

React Hooks: A Beginner's Guide

In the world of React, there's this cool thing called "hooks".These function are specialized tools offered by React to aid in performing a range of tasks within our components. But what precisely are they, and how do they operate? Let's explore their functionality!

React hooks are essentially functions given by React to enable unique functionalities within our components. They allow developers to interact with the fiber tree indirectly, enabling tasks like state management and side effect registration. By using Hooks like useState and useEffect, developers can access and manipulate the fiber tree.

Think of React hooks as keys that unlock hidden potentials within React. They enable us to accomplish various tasks, such as managing data, accessing different sections of our application, and much more.

One important thing to know about React hooks is that their names always start with "use." This helps React know that we're using a hook and not just a regular function.

Another cool thing about hooks is that we can make our own! These are called "custom hooks," and they're like shortcuts that let us reuse code in different parts of our app. It's a bit like having your own toolbox full of handy tools for building stuff😘. Custom Hooks allow you to extract component logic into reusable functions. Custom hooks give us developers an easy way of reusing non-visual logic.So logic that is not about the UI. They are regular JavaScript functions prefixed with use.

Before Hooks were introduced, state and lifecycle methods were only available in class components. With Hooks, you can use state and other React features without writing a class. Now, even simple function-based components can do cool stuff like keeping track of data and making things happen when needed.

There are lots of different hooks that React gives us to use, but the most common ones are useState and useEffect, helping us manage data and make things happen in our components.

And here's the thing about using hooks: there are some rules we need to follow. One rule is that we can only use hooks in certain places inside our components. We can't, for example, use them inside loops or if statements. They have to be used in a specific way to work correctly.

Why? Well, it's because hooks need to be used in the same order every time our component renders. This helps React keep track of everything properly and makes sure our app runs smoothly.

Hooks must be called at the top level in the component body. They cannot be called conditionally or inside loops. This ensures that Hooks are called in the same order each time a component renders.

Also, Only Call Hooks from React Functions: Hooks should only be called from within React function components or custom hooks. They should not be called from regular JavaScript functions, class components, or any other non-React functions. This ensures that React can manage the state of hooks correctly and maintain their proper lifecycle.

So, by following these rules and understanding how hooks work, we can use them to build all sorts of amazing things in our React apps. They're like little magic spells that make our components come to life!

The rules of Hooks in practice

Let's now actually break the main rule of hooks that we just learned about, which is that hooks can only be called at the top level. πŸ‘‡

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);
  let displayMessage;

  if (count === 0) {
    displayMessage = 'Start counting!';
  } else {
    // This is breaking the rule, as useState is called conditionally
    const [message, setMessage] = useState('');
    displayMessage = message;

    setMessage(`Count is ${count}`);
  }

  return (
    <div>
      <h2>{displayMessage}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Counter;

So we get this πŸ˜₯πŸ‘‡

Let's modify the Count component to display the hooks along with their respective numbersπŸ‘‡

import { useState, useEffect } from "react";

const Count = () => {
  const [count, setCount] = useState(0);
  const [text, setText] = useState("");

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  useEffect(() => {
    console.log(`Text changed: ${text}`);
  }, [text]);

  const handleClick = () => {
    setCount((prevCount) => prevCount + 1);
  };

  const handleChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>Click me</button>
      <input type="text" value={text} onChange={handleChange} />
    </div>
  );
};

export default Count;

So in fact, each of the hooks is identified by React by their order number, not some name or anything like that, but really only the number.πŸ‘†πŸ‘†πŸ‘†

To be continued..

Thank you for Reading.πŸ’•

Β