React Hooks

Hooksopen in new window are special functions that let you interact with React features including state management. In addition, hooks make this possible without the need to write JavaScript classes. Hooks were introduced in React 16.8 and are considered one of the easiest ways to incorporate state management into a React application.

Understanding state

Imagine that we wanted to create a dynamic list that allows the user to add new items. We might create an application like this:

function App () {
  const items = [
    'Item 1',
    'Item 2',
    'Item 3'
  ]

  const listItems = items.map(item => <li key={item}>{item}</li>)
  const list = <ul>{listItems}</ul>
  
  function buttonHandler () {
    items.push(`Item ${items.length + 1}`)
  }
  
  return (
    <React.Fragment>
      <button onClick={buttonHandler}>Add Item</button>
      {list}
    </React.Fragment>
  )
}


const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<App />)

Now, unfortunately, this will not work as expected. While new items will be added to the items, they will not be displayed on the page. This is because of how React handles state.

By default, React does not re-render a component when local data is changed. Fortunately, developers can change this behavior by incorporating state into a component. With state, React will listen for changes to local variables and automatically re-render the component. State can be incorporated using the useState Hook.

Using the State Hook

Understanding the useState HookUnderstanding the useState HookThis video is part of the LinkedIn Learning course React.js Essential Training.

The useStateopen in new window hook method is used to declare a state variable, which it necessary to create reactive components.

The useState method returns an array containing two values. The first is an immutable variable holding the value of our state variable. The second is a set function used to update the state variable. When using the useState Methods to declare the state variable, destructuring is employed to retrieve both the value and the function. The value passed to the useState method will be the initial value of the state variable.

function App () {
  // Declaring a new state variable 
  const [items, setItems] = React.useState(['Item 1', 'Item 2', 'Item 3'])

Once a state variable has been declared, the value can be retrieved using the first value in the returned array. In the example above, items is an array, and therefore can be used with the map method.

const listItems = items.map(item => <li key={item}>{item}</li>)

However, because this value is immutable, the array cannot be altered. Instead, the second value of the returned array. The setItems function is used to update the items array. This is accomplished by passing the new value as an argument.

setItems([...items, `Item ${items.length + 1}`])

NOTE

Because items is an array, an array must be passed to the setItems. When adding a new item to the array, the spread syntaxopen in new window is used.

Using the Effect Hook

Working with useEffectWorking with useEffectThis video is part of the LinkedIn Learning course React.js Essential Training.

The useEffectopen in new window method is used to perform side effects in a component. Side effects, including data fetching, setting up a subscription, or manually changing the DOM, can be invoked any time a component is rendered.