React Hook useState()
React Hooks is a set of functions provided by React that allows us to use functional components instead of class components. It is available in React 16.8 or higher projects. Let’s take a closer look at the example below to better understand the useState hook.
Example:
In this example, we define a constant called “App” which is a functional component that accepts props and returns a function body in Person.js. This is a regular functional component, but we can now use React Hooks, such as useState, within the function.
import React, { useState } from 'react';import './App.css';import Person from './Person/Person';persons: [{name: "Ali Bener", age: 43 },{name: "Arslan Eksi", age: 36 },
//The second element is array function allow us to update this state{name: "Levent Mergen", age: 74 }
//such that React is aware of it //and will re-render this componentlinr],otherState: ' some other value'
//The second element is array function allow us to update this state //such that React is aware of it and will re-render this. });
Importing { useState } from React Library
We can import { useState } from the React library to manage state in functional components. Unlike class components, we don’t need to import { Component } from React. The useState hook is essential in managing state and can be called like a normal function, with the previous initial state passed as an argument. We don’t need a render method in functional components, just a return statement with JSX. The useState hook returns an array with two elements, where the first element is always the current state.
(useState({})->
Initially, the second element in the state array will always be a function that we can use to update the state object. By updating the state, React will be notified and re-render the component as needed. To simplify accessing the state and update function, we can use array destructuring, which is a modern JS feature. Here’s an example of how to use it:
(const [] = useState()
First element you can give const [] element any name if you want const.
[personsState]
The second element of the state array will always be a function that allows you to update the state. To make it clearer, let’s name this function “setPersonState”. When using the “useState” hook, we can use destructuring to assign names to the elements of the array returned by the hook. In this case, we can replace “personsState” with “personState” to reflect that it gives us access to the “person” object. Here’s an updated version:
“The second element of the state array will always be a function that allows you to update the state. To make it clearer, let’s name this function ‘setPersonState’. When using the ‘useState’ hook, we can use array destructuring to assign names to the elements of the array returned by the hook. In this case, we can replace ‘personsState’ with ‘personState’ to reflect that it gives us access to the ‘person’ object.”
{this.state.persons[1].name}
//instead
{personsState.persons[1].name}
//We can access person data and
To add a method to a functional component, you can define a function inside the function body of the component. This is a common practice in JavaScript and React, and it is perfectly valid. For example, you can define an onClick function inside the component function and pass it as a callback to an event handler. The this
keyword is no longer used in functional components, so you can simply pass the function name as the event handler, like this:
function MyComponent(props) {
const [state, setState] = useState(initialState);
function handleClick() {
// Do something
}
return (
<button onClick={handleClick}>Click me</button>
);
}
In this example, handleClick
is a function defined inside the MyComponent
function. It can access the state and props of the component, and you can pass it as the onClick
handler for a button.
No parentheses because we don’t wanna execute it immediately. Only this execute the function , when you are using React Hooks the function here as following.
const [personsState, setPersonState]
Second element is array (setPersonState) does not merge whatever you pass in old state.
(setPersonsState) instead its replaces to old state. This is very important. When you ever update a state like this, you have to manually make sure you include all old state data.
This is a normal functional component that We don’t need this.setState anymore because this function doesn’t exist anymore we passed instead setPersonState. Now we just [setPersonState] and we passed our new state object.
import React, { useState } from 'react';import './App.css';import Person from './Person/Person';persons: [{name: "Ali Bener", age: 43 },{name: "Arslan Eksi", age: 36 }, <-------- The second element is array function allow us to update this state{name: "Levent Mergen", age: 74 } such that React is aware of it and will re-render this componentlinr(line 50-57)],otherState: ' some other value'
//The second element is array function allow us to update this state});const [personsState, setPersonState] = useState({ persons: [ {name: "Ali Bener", age: 43 }, {name: "Arslan Eksi", age: 36 }, {name: "Levent Mergen", age: 74 } ],});const [otherState, setPersonsState] = useState ('some other value') console.log(personsState, otherState)const switchHandler = () => { setPersonState({ persons : [ {name: "Erkan Togan", age: 49 }, {name: "Ceren Ates", age: 40 }, {name: "Nevriye Yilmaz", age: 40 }],otherState : personsState.otherState });};return ( <div className="App"> <h1> LEGENDS LIST </h1> <p>This is really working </p> <button onClick={switchHandler}> Switch Name</button> <Person name={personsState[0].name} age={personsState[0].age} /> <Person name={personsState[1].name} age={personsState[1].age}> My Hobbies: Voleyball</Person> <Person name ={personsState[2].name} age={personsState[2].age} /> </div> );}export default App;
//we also made const app with lowercase
Here for example manually adding the other state property and then you have to access the person’s state here. This will just make sure that we copy in the old and untouched other state you can also change this as well. This is a more elegant way to do it. Just copy the useState and pass a value inside. When we click the switched name we update persons and we still have another value because that state is not touched by our call to setPersonsState which only interacts with the first useState result.
According to Reactjs.org about Hooks
React Hooks are a completely opt-in feature. You can try using Hooks in a few components without having to rewrite any existing code. If you don’t want to learn or use Hooks right now, that’s okay too. Hooks are 100% backward-compatible and do not contain any breaking changes, so you can continue using classes if you prefer.
As of React v16.8.0, Hooks are now available for use. However, there are no plans to remove classes from React.
It’s important to note that Hooks do not replace your existing knowledge of React concepts. Instead, Hooks provide a more direct API to the concepts you already know, such as props, state, context, refs, and lifecycle. Additionally, Hooks offer a powerful new way to combine these concepts.
Summary
React Hooks are a collection of functions, with useState being one of the most important. They allow you to add functionality to functional components, as shown in the example where we used useState to manage state. With React Hooks, you don’t need to use class-based components. These hooks are completely optional, backwards-compatible, and available in React version 16.8.0 and higher. They don’t replace your knowledge of React concepts, but provide a more direct API to them, such as props, state, context, refs, and lifecycle. Additionally, Hooks offer a powerful new way to combine these concepts.