Which of the following is a React hook?

Understanding useState in React

useState is one of the built-in hooks that React provides, and it is indeed the correct answer to the quiz question above. It allows you to add state to your functional components, a feature that was only possible in class components prior to the introduction of hooks in React 16.8.

Understanding useState can be the foundation in understanding how React hooks work.

Practical Use of useState

To use useState, you call it inside your component's function body, like so:

const [myState, setMyState] = useState();

useState returns an array with exactly two elements. The first element is the current state value, and the second one is a function that lets you update it. You can name them whatever you like, but it's a convention to use a set prefix on the second function. Initially, myState will hold the initial state, which is undefined if you don't pass any arguments to useState.

Here’s an example in a React component:

import React, { useState } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default MyComponent;

In the example above, we call useState with an initial state of 0. React will remember this initial state between function calls, and if you want to update the state, you can call setCount.

Additional Insights

An important note is that setState does not merge the old and new states as it does in class components. Instead, it replaces the state with the new value. So if your state value is an object, remember to manually merge it:

const [myState, setMyState] = useState({a: 1});
// When updating, merge it with old state
setMyState({...myState, b: 2});

React hooks, like useState, provide simple and clear ways to manage state and side effects in functional components. useState itself is an ideal hook to start learning and mastering React hooks.

Do you find this helpful?