ReactJS – making a simple todo App with React Hooks

0
3206

Finally , react hooks are officially released. I would give a huge change in the way we write react application. We don’t have to deal with classes and setState and some others things…

In this post I want to make a really simple todo app using react hooks, main focus on useState function, how it works and is different with the old way we using state.

What is useState?

useState is a Hook (we’ll talk about what this means in a moment). We call it inside a function component to add some local state to it. React will preserve this state between re-renders. useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together. –https://reactjs.org/docs/hooks-overview.html#-state-hook

Examining the example below:

const [todo, setTodo] = useState("");

We destruct the results from useSate and name it to “todo” and “setTodo”.

The first variable is a state value itself, we use it when we want to get value;

The second variable is a function that is similar to setState that we will use to set/update the state.

The useState function accept one parameter which is the default value of this state.

We can have as many useState as needed

Making the Todo app with react hooks

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
const [todo, setTodo] = useState("");
const [todoList, setTodoList] = useState([]);

return (
<div className="App">
<ul>
{todoList.map(e => (
<li>{e}</li>
))}
</ul>
<input
type="text"
value={todo}
placeholder="type here..."
onChange={e => setTodo(e.target.value)}
/>
<button onClick={_ => setTodoList([...todoList, todo])}>Add</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

First of all, we know that we have to use states for this app, but since hooks coming, we don’t have to make a class to have the state anymore. Functional component looks cleaner and easier.

and don’t forget to import useState from react.

 const [todo, setTodo] = useState("");

This creates a state to hold a single todo that is inputted in the input tag. The initial value is an empty string and we call set state every time the text in the input field is changed.

  const [todoList, setTodoList] = useState([]);

We need another state to holds the list of todos – todoList. and of course, this state must be initialized to an empty array. We then call setTodoList to change this state by adding the current state of todo into this array. That’s what happens in the onClick attribute of button tag.

View all codes here: https://codesandbox.io/s/0423mj2o1w

LEAVE A REPLY

Please enter your comment!
Please enter your name here