Hooks were first introduced to React back in 2019, when React 16.8 was released to the public. Although only being around for a few years they have quickly become the standard when developing with React.
Hooks allow you to hook into the state, and use other React features without having to write a class. There are several different hooks available to use in our application.
Some of the popular ones include:
useState: Helps to pass in the state variables in a functional component.
useEffect: Comes into play for any side effect that needs to be performed after updating the DOM. It takes two arguments: a function and an optional array.
useContext: Helps to build a context API. It is used to share data without passing in props.
Before hooks, we would use classes for React components in order to use state and other React features. Hooks provide a more flexible and simpler way to do this.
Inside your terminal type in the following:
npm: npx create-react-app my-to-do-list
Delete everything between the two <div> tags
Inside of it create a presentational component that displays the title of your application.
Import the Title component
Inside of this json file it will include the tasks for the app, if they are completed and a unique id.
Import the mock-todos.json.
We will need to read the data from the mock-todos.json and will use useState() in order to do that. Import the useState() hook. Declare both toDoList and setToDo. Pass into useState() the todos.
This will hold all of the to-do’s.
Pass in the toDoList in the ToDoList component
This will contain individual to-do’s. Leave it empty for now.
Import the ToDo component we just created. Next, we need to map over our toDoList.
Map over each todo in order to add specific styling to each to-do later on. On the parent <div>, create a className that includes a ternary expression which checks if the todo.done is true, style the text to turn red when a user clicks on the item to be done.
Remove all of the current code and add the below:
Navigate back to App.js where we are controlling the state. Create a new function called toggle() that takes in the unique id. Inside this function map over the toDoList and return the todo.id based on the to-do that was selected.
Add the below:
Pass it into the ToDo component.
Create a handleClick() function that will call the toggle() function and pass into it the unique id.
We have just completed part 1 in this React tutorial series. Make sure to follow along for part 2!