Kishan Zalariya
What are the 2 main differences between state(useState()) and references(useRef())?
By Kishan Zalariya in React on Mar 07 2021
  • Brahma Prakash Shukla
    Oct, 2022 17

    useState()
    The useState() is a Hook that allows you to have state variables in functional components . so basically useState is the ability to encapsulate local state in a functional component. React has two types of components, one is class components which are ES6 classes that extend from React and the other is functional components. Class components a Component and can have state and lifecycle methods: class Message extends React. The useState hook is a special function that takes the initial state as an argument and returns an array of two entries. UseState encapsulate only singular value from the state, for multiple state need to have useState calls.

    Syntax: The first element is the initial state and the second one is a function that is used for updating the state.

    const [state, setState] = useState(initialstate)

    We can also pass a function as an argument if the initial state has to be computed. And the value returned by the function will be used as the initial state.

    const [sum, setsum] = useState(function generateRandomInteger(){5+7);})
    The above function is oneline function which computes the sum of two numbers and will be set as the initial state.

    Importing: To use useState you need to import useState from react as shown below:

    import React, { useState } from “react”
    Creating React Application:

    Step 1: Create a React application using the following command:

    npx create-react-app foldername
    Step 2: After creating your project folder i.e. foldername, move to it using the following command:

    cd foldername

    useRef

    The useRef hook is the new addition in React 16.8. Before proceeding to this article there is a prerequisite to know about the ref in react.
    The useRef is a hook that allows to directly create a reference to the DOM element in the functional component.

    Syntax:

    const refContainer = useRef(initialValue);
    The useRef returns a mutable ref object. This object has a property called .current. The value is persisted in the refContainer.current property. These values are accessed from the current property of the returned object. The .current property could be initialised to the passed argument initialValue e.g. useRef(initialValue). The object can persist a value for a full lifetime of the component.

    • 3
  • Aadesh Saxena
    Mar, 2021 9

    basically, useState would be used in the cases when we want to maintain and update the properties during the re-rendering of view.useRef we will use if we want to persist the values throughout the lifetime of the component.

    • 3


Most Popular Job Functions


MOST LIKED QUESTIONS