O'Reilly logo

React Design Patterns and Best Practices - Second Edition by Carlos Santana Roldan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

React hooks

React Hooks are a new feature in React 16.8. They let us use state, and other React features, without writing a class component, for example:

  import React, { useState } from 'react';   function Counter() {    // times is our new state variable and setTimes the function to update that state.    const [times, setTimes] = useState(0); // 0 is the initial value of times    return (      <div className="Times">        <p>Times clicked: {times}</p>        <button onClick={() => setTimes(times + 1)}>Click it!</button>      </div>    );  }   export default Counter;

As you can see, useState creates the new state and the function to update the state, you have to define the initial value when you called – not just numbers, you can add any type of value, even objects:

  import ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required