Understanding React Hooks - UseState

ยท

4 min read

Understanding React Hooks - UseState

React hooks are features of React that allow us to use state and other react lifecycle features without writing a class, that is to say, they can only be used inside functional components. React has many hooks that it uses for state management and lifecycle methods, and are mostly preferred use due to its reusability and testability.

In this tutorial, we would be talking about the most basic React hook - UseState

UseState

This hook allows us to track states in functional components, they are used for basic state management in simple projects which require non-complex state handling. UseState function stores an initial state of a variable and also a function to update the state. UseState can be applied in cases like:

  • Tracking the state of variables
  • Storing data from an API call
  • Conditional rendering
  • Toggling of flags/buttons (boolean state)

This function can cause your component to re-render whenever the update function is called. Note, UseState should be called when an event happens and not be written at the top level of the functional component which will lead to an infinite loop due to the state update causing a re-render and function evaluation which also has the state update call inside it. For example:

import {useState} from 'react';

const Example = () => {
      const [name, setName] = useState('initial value');

     setName('Favour')
     console.log(name)
     return (
          <div>
              <h1> My name is {name} </h1>
          </div>
       )
}

export default Example;

Don't use UseState like the code above, there are no restrictions on when the state is being updated so the setName is being called continuously and leads to an infinite loop. Instead, we are going to be using a button click event to change the state of the variable.

import {useState} from 'react';

const Example = () => {
      const [name, setName] = useState('initial value');
      const clickHandler = () => {
            setName('Favour')
      }

     return (
          <div>
              <h1> My name is {name} </h1>
              <button type='button' onClick={clickHandler}>Change Name </button>
          </div>
       )
}

export default Example;

In this case, the update state call is only executed when the button event occurs and the state is changed and a re-render occurs to reflect the current state. In the next example, we would be using useState for conditional rendering - toggling on and off a state(true/false)

import {useState} from 'react';

const ConditionalRendering = () => {
      const [show, setShow] = useState(false);
      const toggleHandler = () => {
           setShow(!show)
      }
     return (
          <div>
              {show ? <h1> My name is favour </h1> : <></>}
              <button type='button' onClick={toggleHandler}>{show ? "hide" : "show"}  Name </button>
          </div>
       )
}

export default ConditionalRendering;

In this example, we are using a state variable show to determine the display of a line of text. The toggling action is being done by a button whose text also is determined by the state. We are using a ternary operator for conditional rendering which evaluates a variable and if true returns the first expression and if false returns the second. So by the click of the button the call to update the state to the opposite of its current state, which will now be used in the ternary operator to render or hide the element h1 and change the display text of the button. Way cool right...๐Ÿ˜Ž๐Ÿ˜Ž

In our last example, we will be displaying inputted letters from a form input as its being typed using useState to continuously update the state.

import {useState} from 'react';

const InputRendering = () => {
      const [input, setInput] = useState('');

     return (
          <div>
              {/* displays the inputted texts in this h1 element */}
               <h1> {input} </h1> 
              <input type='text' value={input} name='name' onChange={(e) => 
                       setInput(e.target.value)} />
          </div>
       )
}
export default InputRendering;

And this little line of code does all the magic necessary, feeling like a code wizard๐Ÿง™๐Ÿง™๐Ÿง™ already.

That's it about UseState and its usage, a lot more can be done with this hook. With the most basic react hook being dealt with, watch out for the next tutorial on another great react hook - UseEffect

Thanks for reading๐Ÿ™‚๐Ÿ™‚.

ย