react js-tutorial

React Hooks

The new feature that was added to React 16.8 is called hooks. Without creating a class, you can use state and other React capabilities. Hooks are the functions that allow function components to “hook into” state and lifecycle elements of the React framework. In a classroom, it is ineffective.

Since Hooks are backward-compatible, they don’t include any fundamental modifications. It also doesn’t take the place of your understanding of React ideas.

useState

Within a function component, you can use local state with useState. This function takes an initial state parameter and returns a variable with the value of the current state (which need not be the starting state) and another function to update this value.

Declare state variable

Declaring a state variable is as simple as calling useState with some initial state value, like so: useState(initialStateValue).

const DeclareStateVar = () => {
  const [count] = useState(100)
  return <div> State variable is {count}</div>
}

Update state variable

Updating a state variable is as simple as invoking the updater function returned by the useState invocation: const [stateValue, updaterFn] = useState(initialStateValue);.

Here’s the code responsible for the screencast above:

const UpdateStateVar = () => {
  const [age, setAge] = useState(19)
  const handleClick = () => setAge(age + 1)

  return (
    <div>
      Today I am {age} Years of Age
      <div>
        <button onClick={handleClick}>Get older! </button>
      </div>
    </div>
  )
}

Why does the React useState Hook not update immediately?

If you find that useState/setState are not updating immediately, the answer is simple: they’re just queues.

React useState and setState don’t make changes directly to the state object; they create queues to optimize performance, which is why the changes don’t update immediately.

React Hooks and multiple state variables

Multiple state variables may be used and updated from within a functional component, as shown below:

Here’s the code responsible for the screencast above:

const MultipleStateVars = () => {
  const [age, setAge] = useState(19)
  const [siblingsNum, setSiblingsNum] = 
    useState(10)

  const handleAge = () => setAge(age + 1)
  const handleSiblingsNum = () => 
      setSiblingsNum(siblingsNum + 1)

  return (
    <div>
      <p>Today I am {age} Years of Age</p>
      <p>I have {siblingsNum} siblings</p>

      <div>
        <button onClick={handleAge}>
          Get older! 
        </button>
        <button onClick={handleSiblingsNum}>
            More siblings! 
        </button>
      </div>
    </div>
  )
}

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.