React Hooks

React Hooks

Keeping your components hooked on efficiency!

Introduction

React hooks are an essential part of the react framework, it was developed by facebook in the May 2013. It was made to efficiently update the UI by selectively rendering only the components that had changed, minimizing DOM manipulation and improving performance.

Do you think its hard? yes? no? let's me make it easy for you

What are hooks?

Hooks are function's that can dynamically change the state of any element in a react application. for eg: show a form on button click

These are what makes react soo cool and fun to code with

The react hooks that are used most commonly are:

  • useState hook

  • useEffect hook

  • useRef hook

These are used primarily, although there are many others like useContext, useReducer, useContext, useMemo...etc

useState hook

useState hook is used to change the value of a variable dynamically.

Now you may think why not use a simple variable? Since,we can change the value there too. But the difference is react will not know when to rerender the element, if we use useState variable it will always rerender when value changes.

const [variable, setVariable] = useState<number>(10);

In the above code, we are using useState hook, it has a initial value of 10 and returns an array of 1 variable having value 10 and a setter function setVariable to change the value.

setVariable(20); // this is to change value to 20

You don't directly modify the state variable itself. Instead, you use the setter function (setVariable in this case) provided by useState to update the state. This ensures that you follow React's principles of immutability, which helps prevent unexpected side effects and makes your code easier to reason about.

import React, { useState } from 'react';

const Counter: React.FC = () => {
  const [count, setCount] = useState<number>(0);
  return (
    <div>
      <p>You clicked {count} times</p> {/* value is changed here */}
      <button onClick={() => setCount(count + 1)}>{/* setter function helps to change value */}
        Click me
      </button>
    </div>
  );
}
export default Counter;

useEffect hook

useEffect hook is used to run a piece of code when the page loads for the first time and when the value of a variable which it is dependent on changes.

useEffect is used in functional components to perform side effects. These side effects may include data fetching, subscriptions, or manually changing the DOM.

It takes 2 arguements, the function which needs to run and an array of dependent variables(it is optional).

useEffect(() => {},[]);

Consider a senario where we need to query the database for user information, now we only want it query when page load's and if user updates his information. we can use useEffect in such cases.

Let's see how we can implement this

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

const ExampleComponent:React.FC = () => {
  const [userData, setUserData] = useState<userType>({});
  useEffect(() => {
    //query  to db
    const userDataFromDb : userType  = queryDB(); //dummy function for demo
    setUserData(userDataFromDb);  //store in useState variable
  },[userData]); // we pass array of depenedent variables soo as to refetch on value change
    //[]); can be empty, runs only once   

  return (
    <div>
      <p>{userData}</p>
      <button onClick={() => setUserData({})}>
        Refresh data
      </button>
    </div>
  );
};
export default ExampleComponent;

User data is fetched when pages loads for first time and then fetched again if refresh is clicked since it is dependent on userData variable or if the is reloaded.

useRef hook

useRef hook is used to maintain a refernce to a object to change its properties and unlike useState will not rerender when value is changed.

It is a replacement for document.getElementById in vanilla Javascript.

we need to add it as ref to a html tag after declaration.

const ref = useRef(null);

<div ref={ref}></div>

Example usage can be when we need to hide a element after a condition is met.

import React, { useRef } from 'react';

const ExampleComponent: React.FC = () => {
  // Create a ref to store a reference to the input element
  const divRef = useRef<HTMLDivElement>(null);
  // Function to hide the div element when the button is clicked
  const hideDiv = () => {
    // Access the current property to get the reference to the div element
    if (divRef.current) {
      divRef.current.style.display = 'none'; // hide the div by setting its display property to 'none'
    }
    // Alternatively, you can achieve the same using document object:
    // document.getElementById('myDiv').style.display = 'none';
    // Note: You would need to add an id="myDiv" attribute to the div in your TSX
  };

  return (
    <div>
      {/* Attach the ref to the div element , can add id="myDiv" for div below to do using document*/}
      <div ref={divRef}>This div will be hidden when the button is clicked</div>
      {/* Button to hide the div element */}
      <button onClick={hideDiv}>
        Hide Div
      </button>
    </div>
  );
};
export default ExampleComponent;

This is how useRef is used in react.

Conclusion

React Hooks revolutionize functional components, empowering them with state and lifecycle features. They streamline code, enhance reusability, and simplify complex logic, making React development more efficient and enjoyable.

Well now you know how easy it is, right? let's get coding

React docs: click here

Note: for any corrections do reach out to me using my socials present in the navbar.