There is some universal truth to the idea that the more you know about something, the more you realize how much more there is to learn on the topic. A great example of this is learning about React when it comes to coding. You barely have time to get comfortable writing code and along comes an entire new way to write and think about code.
import { useState } from "react";
It is a simple line of code but it allows us to do so much. To state it simply, the useState
hook is a feature in React that allows functional components to have state. State is used to manage data that may change over time and will trigger re-renders of the component when it is updated.
That is all well and good but what does that actually mean when you set out to write something. Say you are writing an app to track daily tasks and you want to be able to add new tasks to your list. By using react and states, you have the ability to create interactive user interfaces! Lets see how with a few examples of code you might write in a NewTaskForm component.
const initialData = { text: "", category: "" };
const [newTask, setNewTask] = useState(initialData);
This component is responsible for rendering a form where the user can input data for a new task. It utilizes the useState hook to manage the form's state, specifically the newTask object, which stores the text and category of the new task.
To actually add the information you want, you need a function to be called whenever the user adds something in the input field or selects a category from the dropdown (for this project I went with typing in the input and selecting from a drop down but it is ultimately up to you).
const handleChange = (e) => {
setNewTask({ ...newTask, [e.target.name]: e.target.value });
};
Here the handleChange function is called whenever the user interacts with the input and drop down. It then updates the 'newTask' object with the new values.
Next you need to think about what happens when the form is submitted. A handleSubmit is triggered, you want to prevent default form submission behavior (resetting your page), call a function to actually submit it (in this example we called it onTaskFormSubmit
and we passed it down from a parent component with the newTask
object as an argument and finally reset the form fields to their initial state that we defined above.
const handleSubmit = (e) => {
e.preventDefault();
onTaskFormSubmit(newTask);
setNewTask(initialData);
};
There are a few more things going on in other components that make this code really sing, but this small little cut away shows how React can allow you to manipulate the data so the front end of you website gives the user a fully interactive experience without losing the initial information that was loaded. As I learn more about coding, I realize that everything is built on things I learned the day before. This is just scratching the surface of what states and React can help you do and I know I am looking forward to seeing what comes next.
Top comments (0)