What are React Hooks?
They are functions in React that allow you to add react functionality to function based components.
What is the useState hook?
The useState hook is used to add state to a function-based component. The syntax will follow a common pattern:
const [listEntry, setListEntry] = useState('')
-
listEntry
is the state variable. -
setListEntry
is the function used to edit the state variable. Note, you should only edit the state variable through this function. -
useState('')
is setting the initial value of the state variable. In this case, whenlistEntry
is initialized, it equals an empty string.
This example lets you enter a value, then add it to a bulleted list:
import { useState } from "react";
const App = () => {
const [listEntry, setListEntry] = useState('');
const [listEntries, setListEntries] = useState([]);
const handleInputChange = (e) => {
setListEntry(e.target.value);
};
const handleAddButtonClick = () => {
setListEntries((listEntries) => [...listEntries, listEntry]);
setListEntry("");
};
return (
<div>
<input type="text" value={listEntry} onChange={handleInputChange} />
<button onClick={handleAddButtonClick}>Add</button>
<ul>
{listEntries.map((entry) => {
return <li>{entry}</li>;
})}
</ul>
</div>
);
}
-
const [listEntries, setListEntries] = useState([]);
we are creating a valuelistEntries
and initially setting it as an empty array. This will hold our list items. -
<input type="text" value={listEntry} onChange={handleInputChange} />
each time you enter a character in this input, thelistEntry
variable is being updated to what you are typing. -
<button onClick={handleAddButtonClick}>Add</button>
when clicked, the value oflistEntry
is being appended to thelistEntries
array. -
{listEntries.map((entry) => {return <li>{entry}</li>;})}
the values inlistEntries
are being rendered in a bulleted list.
More information can be found in Reacts official documentation: https://reactjs.org/docs/hooks-state.html
Leave a comment if you have any feedback or questions.
Top comments (1)
Many early birds have already started using this custom hooks library
in their ReactJs/NextJs project.
Have you started using it?
scriptkavi/hooks
PS: Don't be a late bloomer :P