Logo

dev-resources.site

for different kinds of informations.

React HooK= { Briefly Explained};

Published at
8/19/2024
Categories
hooks
react
jsx
javascript
Author
marlonmunoz
Categories
4 categories in total
hooks
open
react
open
jsx
open
javascript
open
Author
11 person written this
marlonmunoz
open
React HooK= { Briefly Explained};

useState is a React Hook that allows you to add state to your components by returning an array with two variables: state, setState. The current state and the function that becomes the setter function when it is called. It can be used to track data or properties that need to be tracked in an application, such as strings, numbers, booleans, arrays, or objects.
Example:

const [state, setState] = useState();
Enter fullscreen mode Exit fullscreen mode

In simple terms, state will change at some any point and it needs to be updated, therefore 'setState' will update the state, triggering a re-render of your components over time.

In addition, useState can hold any kind of Javascript value, including objects. Something to ALWAYS keep in mind is that you should never change objects that you hold in React state directly. First, you need to create a new one or create a copy of an existing one and then setState to the new copy. For example:

// Objects
const [state, setState] = useState({name: 'Marlo', age: 56});

const updateName = () => {
  setState({...state, name: 'Karlo'});
};

const updateAge = () => {
  setState({...state, age: 96});
};
---------------------------------------------------------------------------------
// Arrays
const [array, setArray] = useState([1, 2, 3, 4, 5]);

const addItem = () => {
  setArray([...array, 6]);
};

const removeItem = () => {
  setArray(array.slice(0, array.length - 1));
};
Enter fullscreen mode Exit fullscreen mode

To use useState in a React component, first you need to import it form React by writing the following code in the top of the component's page in two different ways, both work perfectly so you can choose your poison.

import React from 'react'; 
import {useState} from 'react';
Enter fullscreen mode Exit fullscreen mode

or you can write in one line

import React, {useState} from 'react';
Enter fullscreen mode Exit fullscreen mode

React Hook useState can be called at the top level of a component or within custom hooks but not inside loops or conditions.

const [initialState, setInitialState] = useState();
Enter fullscreen mode Exit fullscreen mode

the initialState is only used during the initial render and will be disregard in subsequent renders.
The initialState function is passed to the setInitialState function, it takes the previous state as an argument, and returns a newState.

Furthermore, in my opinion, there are no special rules about where you can and cannot use Hooks in React. Of course, you have to be cautious and tactical to keep you code organized.

In one of my projects, building a SPA(Single Page App) there were various components to achieve my goal. The secret to be well organize, is to keep track of your components. For instance, your App.js component will use {useState} depending on what type of data needs updating.
Let's introduce another powerful hook from React called: {useEffect} and use it along {useState} to explain how these hook perform operations on data. The following example comes from my App.js component I used in a recent project. I was working with a db.json file data for toys that will help children development for the first year. This is my endpoint http://localhost:4000/toys to help you understand the process of how {useState} and {useEffect} work inside inside of an application component.

First: Initialize State:

const [toys, setToys] = useState([]);
Enter fullscreen mode Exit fullscreen mode
  • This line initializes a state variable toys with an empty array [] as the initial value.
  • setToys is a function that will be used to update the toys state.

Second: Fetch Data on Component Mount:

useEffect(() => {             
    fetch("http://localhost:4000/toys")  
      .then(response => response.json())
      .then(data => setToys(data)); 
  }, []);
Enter fullscreen mode Exit fullscreen mode
  • The {useEffect} hook is used to perform side effects in the component.
  • The function inside {useEffect} will run once when the component mounts because the dependency array ([]) is empty.

Third: Fetch Toys Data:

  • fetch("http://localhost:4000/toys")
    • This line makes a GET request to the specified URL to fetch toys data.
  • .then(response => response.json())
    • the response from the fetch request is converted to JSON format.
  • .then(toysData => setToyData(toysData));
    • The JSON data (toysData) is used to update the toys state using the setToys function.

To understand more in depth how both {useState, useEffect} work you can visit the official React website. In addition, another helpful source is w3schools website, that is my personal favorite. It goes straight to the point with examples that you can try in their own browser. Lastly, if you need a more technical source, the mdn web docs will help you.

hooks Article's
30 articles in total
Favicon
Hooks Behind The Scenes 3, UseRef!!!
Favicon
A Complete Guide to All React Hooks for Beginners
Favicon
Using useReducer for Complex State Logic
Favicon
Descobrindo o useCallback do React
Favicon
Discovering React’s useCallback
Favicon
Mastering Code Quality in Laravel: Pint with Git Hooks and Docker
Favicon
React: leveraging custom hooks to extract reusable logic
Favicon
Hooks Behind The Scenes 2, useState!!
Favicon
Mastering React Functional Components: Hooks, useEffect, and Lifecycle Explained
Favicon
JSHooks API compare to CHooks
Favicon
The Ultimate Guide to Wall Hanging Hooks and Display Systems for Your Home and Office
Favicon
How to Detect if an Element is in View with React
Favicon
React useQuery : A Complete Guide
Favicon
{useState} HooK { Briefly Explained};
Favicon
React HooK= { Briefly Explained};
Favicon
What is useState?
Favicon
Actions - React 19
Favicon
React controlled and uncontrolled hooks
Favicon
React Concepts: Hook Proximity
Favicon
Demystifying React's useState Hook: A Comprehensive Guide
Favicon
Mastering React Hooks: Best Practices for Efficient and Maintainable Code
Favicon
Designing React Hooks for Flexibility
Favicon
Unleashing the Power of React Custom Hooks
Favicon
Understanding Context Hooks in React: A Beginner's Guide
Favicon
3 Ways To Create Engaging React Loading Screens with Hooks
Favicon
Understanding the useInteractionTimer Hook: Measuring Component Interaction Time in React
Favicon
Cats Fatc's Quick project
Favicon
All About Custom Hooks: Supercharge Your React Components
Favicon
Suggestion for new syntax of React reducers + context
Favicon
How To Define Typescript onChange Event In React

Featured ones: