DEV Community

Tauan Camargo
Tauan Camargo

Posted on

React Hooks, What is it? How to use it? Pt.1 - Using "useState"

On this first part, I'm going to show you how to use react hooks in a sample react application, that application you'll be able to add books to your list, think the possibilities, we'll use useState(), useEffect() and useCallback().

First Step: Create Project

  • You will need to install create-react-app to your machine, use this command to install npm install -g create-react-app;
  • So now you can generate the project typing npx create-react-app books;
  • Your project folder will contain this paths and files: project folder
  • Delete this file App.js and create a new file with the same name;
  • On your new file create something like that:
import React from 'react';

export default function App() {
  return <h1>Hello World!</h1>
};
Enter fullscreen mode Exit fullscreen mode

Second Step: Using useState()

In react version before 16.8 to create a Component that has a state, you should to create a Class Component like that:

import React from 'react';

class App extends React.Component {
  state = {
    title: 'Hello World!',
  }

  render() {
    return <h1>{this.state.title}</h1>
  }
};

export default App;
Enter fullscreen mode Exit fullscreen mode
  • Okay now we're going to put this in our context:
import React from 'react';

class App extends React.Component {
  state = {
    books: ['Javascript', 'React'],
    newBook: '',
  }

  handleBookInput = e => this.setState({ newBook: e.target.value });

  addBook = () => {
    this.setState({
      books: [...this.state.books, this.state.newBook],
      newBook: '',
    });
  }

  render() {
    // if you don't know what is <></> is short way to use <React.Fragment> :D
    return (
      <>
        <input
          value={this.state.newBook}
          onChange={this.handleBookInput}
          placeholder="add here you new book"
          onKeyPress={e => e.key === 'Enter' && this.addBook()}
        />
        <button onClick={this.addBook}>Add Book!</button>
        <ul>
          {this.state.books.map(
            (book, index) => <li key={index}>{book}</li>
          )}
        </ul>
      </>
    )
  }
};

export default App;
Enter fullscreen mode Exit fullscreen mode
  • let's re-build this file to a functional component and let's use useState:
// We need to import useState from react
import React, { useState } from 'react';

export default function App() {
  /* When we declare a state variable with useState,
  it returns a pair — an array with two items.
  The first item is the current value,
  and the second is a function that lets us update it.
  Using[0] and[1] to access them is a bit confusing because 
  they have a specific meaning.
  This is why we use array destructuring instead. */

  /* 
  const booksStateVariable = useState(['Javascript', 'React']);
  const books = booksStateVariable[0];
  const setBooks = booksStateVariable[1];
  */

  /* To be more pretty and readable we use the way bellow,
  now you don't need to use this.state.books, just use books as a state 
  variable :D;   
  */

  const [books, setBooks] = useState(['Javascript', 'React']);

  /*We'll create an addBook function to save this new book in books array,
  what this setBooks do? Answer: It do something like that to you => [...books, the_new_value],
  in this first part of article, we'll put the 'Test' value locally, 
  in next part i'll show the next steps.
  */
  const addBook = () => setBooks('Test');

  return (
    <>
      <button onClick={addBook}>Add test book!</button>
      <ul>
        {books.map((book, index) => <li key={index}>{book}</li>)}
      </ul>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

to be continued

React hooks Pt. 1 - Link here
React hooks Pt. 2 - Link here

Top comments (0)