DEV Community


Posted on

useState in React.js

React is a powerful JavaScript library that is used by many developers to build modern web applications. It uses "component based architecture" which results in code that runs more efficiently, improving performance. React also uses declarative programming as opposed to imperative programming, which alongside the component based architecture promotes the building of clean and clear code that can be reused easily. This blog post will focus on useState, a critical hook in React used to manage state within components.

The useState hook is a built-in feature in React that allows functional components to manage state. When you use the useState hook, it returns an array with two elements: the current state value and a function to update that state. By calling this update function, React will re-render the component, reflecting the updated state in the user interface. While it is common to use useState to keep track of a boolean value, useState can contain values of many data types; such as strings, numbers, objects and arrays.

import React, { useState } from 'react';

function ExampleComponent() {
  const [isActive, setIsActive] = useState(false);

  function handleClick() {

  return (
      <button onClick={handleClick}>
        {isActive ? 'Active' : 'Inactive'}
Enter fullscreen mode Exit fullscreen mode

The code in the above example initializes a state variable in the third line with the variable callout. The click event listener within the JSX return on the button references the handleClick() function, calling the state setter function and reversing the value of the state. This results in the other value in the ternary expression being displayed.

State can also be used to keep a client side log of data that has been fetched from the back end or another source online such as an API.

import React, { useState } from 'react';

function ExampleComponent() {
   const [data, setData] = useState([])

   useEffect(() => {
      .then(res => res.json())
      .then(fetchData => setData(fetchData)
    }, [])

Enter fullscreen mode Exit fullscreen mode

In this example, the variable data is initialized as a state variable. The data grabbed by the fetch is placed within the state variable by calling the setter function with an argument of the data from the fetch. The console.log(data) at the bottom of this example will log all of the data grabbed by the fetch, as the state has been updated to reflect that data.

When using state in React, there are some best practices that can help keep your code organized and readable. Separating different state concerns into multiple state variables is best practice as this makes it easy to track the state of a specific variable as code executes. Having multiple functions refer to and perhaps change a single state can lead to unexpected outputs or loss of data.

In conclusion, the useState hook in React is a powerful tool for managing state within functional components. By using useState, you can easily create interactive and dynamic user interfaces. We explored the basics of useState, including its syntax, usage with simple and complex state, and important tips for effective usage. By following best practices, separating state concerns, utilizing functional updates, and considering performance implications, you can harness the full potential of useState and build robust and scalable React applications. With a solid understanding of useState and its capabilities, you're well-equipped to enhance your React development skills and create engaging user experiences in your web applications.

Top comments (0)