useState () Hook in React.

useState () Hook in React.

She Code Africa Nairobi's photo
·

4 min read

Introduction.

Gone are the days of solely relying on class components—introducing useState() and a myriad of other built-in hooks that revolutionize how we manage state and wield React's features.

Ready to elevate your coding game ? Let's delve deeper into understanding useState() and unlock its full potential.

Hooks were added in React version 16.8. In version 16.8 and prior versions of React, state, and other React features could only be accessed within class components. useState() is one of React's inbuilt hooks among many others. In this article, we will explore its depth and uncover its versatility.

What is useState()

useState is a React hook that allows a state to be added to a functional component. State is a built-in React object that holds any data or properties that can change over time and affect the UI regarding how a component appears or behaves. State allows dynamic UI changes to be rendered. These dynamic UI updates are responses to triggers such as user input for example button clicks or system-generated events such as content or image loading.

How to use useState() hook.

To use the useState hook, you need to import it at the top of the file from React.

 import React, { useState } from 'react';

You can then call it inside your functional component :

 const [state, setState] = useState(initial value)

useState hook returns the current state of the component and its setter function(a function to update the current state). The hook takes an initial state value as an argument and returns an updated state value whenever the setter function is called. When a component is rendered, its state is assigned an initial value or the value set to it by the setter function. If the initial value is not provided, the default value becomes undefined. Below is a demonstration.

import React, { useState } from 'react';
const App = () => {
const [userName, setUserName] = useState();
    setUserName('Mary');
return (
<p>Hello {userName}</p>
); };

In the code above, the value that userName holds is undefined since an initial value is not provided. If the initial value we wanted to assign to userName were a string, then we would call the hook with an empty string value, then call the setter function with the new value like so.

const [userName, setUserName] = useState('');
setUserName('Mary');

What can useState hold?

useState stores any value like string, number, array, boolean, object, and even function.

import React, { useState } from 'react';
const App = () => {
    const [number, setNumber] = useState(0);
    const [string, setString] = useState('')
    const [object, setObject] = useState({})
    const [array, setArray] = useState([])
    const [function, setFunction] = useState(() => functionName())
return (
        // ...
); 
};

However, if you pass a function as initialState it will be treated as an initializer function. React will call your initializer function when initialising the component and store its return value as the initial state.

Let's look at a demonstration of a functional component that uses useState to toggle a user's active status.

import React, { useState } from 'react';
const UserProfile = () => {
  const [isActive, setIsActive] = useState(false);
  // Function to toggle user's active status
  const toggleActiveStatus = () => {
    setIsActive(!isActive);
  };
  return (
    <div>
      <h2>User Profile</h2>
      <button onClick={toggleActiveStatus}>
        {isActive ? 'Deactivate' : 'Activate'} User
      </button>
</div> );
};
export default UserProfile;

In the above code, we import the useState hook from React. We then create two variables, isActive and setIsActive, and assign it an initial value of false as the user is currently deactivated. In the Jsx section, we create a user profile section and include a button where we can toggle the user's status. Since the current isActive is currently false, the text on the button is Activate User.

The button has an onClick event handler. Within this onClick handler, we create toggleActiveStatus function by using the setter we declared earlier called setIsActive. In the toggleActiveStatus function, we use the setter function setIsActive to change the value to !isActive. When the button is clicked again isActive will change to true, the user will be activated and the button text will change to Deactivate User.

Conclusion.

Armed with this knowledge on useState hook(), you can effortlessly toggle a component's status, opening doors to limitless possibilities in your React projects.

To read more articles written byhttps://hashnode.comSally Nzungula or connect on LinkedIn with Sally Nzungula.

Keep Up skilling - Its the key to unlocking your full potential in the ever-evolving tech landscape!

Cover Photo by Lautaro Andreani on Unsplash.