Quick Summary: The blog comprises of the journey for the beginners; who have started using
React useState. Let’s have an in-detail look at useState in React hooks. It will help to get your hands on useState in React theoretically and practically.
1. Overview: What does React hooks mean?
2. Why React hooks?
3. How to work with useState hook?
4. What does useState in React return us?
5. Conclusion
Overview: What Does React Hooks mean?
React Hooks are built-in functions that allow us to hook into React state and lifecycle from the functional(stateless) component.
From this, we can assume that using hooks makes it possible to manipulate our functional component’s state. There’s no need to convert our functional component to a class component for handling the React state. Oops, there’s one more thing that should be kept in mind while working with React Hooks: Hooks can’t be used inside the class component.
Your component should be a functional component if you want to access hooks.
React Hooks not only allows us to manipulate and work with states but also helps us in avoiding various lifecycle methods: componentDidMount, componentDidUpdate, and componentWillUnmount. Alternatively, we can use useEffect, React built-in hooks, for the same. Okay, this can be said as an overview of React Hooks.
Why React to Hooks?
We all are well aware of the benefits of React provided by its functional component.
Moreover, it’s difficult to use stateful logic amongst components. If you’re familiar with, react, then ,you might be knowing about render props and high-order component, which tries to solve the problem of attaching reusable behavior to a component. But, while using this, you have to organize your components. And this will make your code more difficult to understand. If you observe this in your React DevTools, you’ll find a “wrapper hell” of components. With React Hooks, you can reuse the stateful logic without manipulating your component hierarchy.
Another perk of using React Hooks can be said that it simplifies your code and component structure. Those who had worked with React would be familiar with lifecycle and of course the bugs and inconsistencies due to it. React Hooks allow you to split one component into different small functional components. Because of this division, the bugs caused due to unwanted interference of unrelated logic amongst various lifecycle will be taken care of.
React Hooks which are mainly in use:
- useState: Helps in manipulating state within the functional component.
- useEffect: Helps in working with lifecycle inside the functional component.
- useContext: Acquires the value returned from React.createContext and returns the current context value, which is given by the nearest context provider for that context.
Among the various React hooks, useState will be the concern of this blog, so the main focus will be on useState in React functional component. Okay, let’s dive into it.
How to work with useState hook?
function useStateExample() { // Declaring useState hook. const [weight, setWeight] = useState(45); console.log(weight); // 45 setWeight(50); console.log(weight); // 50 // .. }
The line const [weight, setWeight] = useState(45); declares a state variable named weight and a function setWeight which allows you to update the preceding state variable, here weight.
And there must be a question about the initial value of the state variable! While using the useState hook, what value would be assigned to the state before calling the function?
Look at the snippet, and you’ll find your answer. Yes! The value enclosed in curved brackets used while declaring the state variable, is denoted as the initial value of the state variable. Here the initial value, that is the first value before updating the state using the function, of weight is 45.
Looking for exceptional React development services for your project?
Get in touch with the best React development company to implement your goals and build best-in-class apps.
So, are we clear? Okay. Good! Let’s proceed.
We have 45 as our initial value. After that, when we want to update the value of weight, we will use setWeight(50)- any desired value can be passed. Easy and less complicated! isn’t it?
It’s not even mandatory that the state variable has to be an object. Although it can be, there’s no compulsion.
—————————————————————————————————————————————–
There’s one thing you should follow while working with useState hook:
Declare your state variables and function related to it at the top of your functional component. Don’t call hooks inside loops, conditions or nested functions.
—————————————————————————————————————————————–
What does useState in React return us?
Now, heading towards what does useState in React returns us? It returns a pair of values: the current state variable and a function that updates that particular variable.
Declaring multiple state variables : function MoreExamplesOfHooks() { const [weight, setWeight] = useState(45); const [vegetable, setVegetable] = useState(‘Tomato’); const [name, setName] = useState([{ firstName: 'Neha' }]); //.. }
Basic example using useState in React.
import React, { useState } from "react"; export default function HooksExampleUsingState() { const [buttonValue, setButtonValue] = useState("Click me!"); return ( < button onClick={() => setButtonValue("Thanks for clicking!")} > {buttonValue} < /button > ); }
Here, state variable name buttonValue and function which update buttonValue is setButtonValue. As we learned before, the value within the curved bracket is said to be the initial value. Thus, Click me! is displayed on the button. As soon as the button is clicked, setButtonValue is called. Remember, the button already had its initial value. But, now the function call will update it. Thus, the value displayed on the button will be Thanks for clicking!.
Since there is no updation in the value of the state variable of React usestate hook, no changes will further appear.
React will maintain this state variable between re-renders.
If required, you can also call the function as a regular function rather than using an inline arrow function.
import React, { useState } from "react"; export default function Button() { const [buttonValue, setButtonValue] = useState("Click me!"); function handleClick() { return setButtonValue("Thanks for clicking!"); } return < button onClick={handleClick} >{buttonValue}< /button >; }
Conclusion:
React Hooks are built-in functions that allows you to hook into React state and lifecycle in functional components.
With React Hooks, you can reuse the stateful logic without manipulating your component hierarchy and get rid of “wrapper hell.” Hooks in React makes your code look simple and clean.
const [weight, setWeight] = useState(45) weight: state variable setWeight: a function that manipulates the value assigned to weight useState(45): useState hook which initializes the value of weight with 45.
useState hook returns a pair of values: the current state variable and a function that updates that particular variable.
Now, get your hands-on React Hooks and start exploring a new version of React.js. If you are looking for ReactJS experts who can help you get the job done, then hire ReactJS developers from us today to leverage their top-of-the-line expertise.