Understanding UseState in React

Understanding UseState in React

Hello Everyone, I have not written an article here for a long time; and I decided this year to put out more articles on my Hashnode blog, at least once a week. So here is me putting out an article this week.

Today, I will be talking about usestate React hook. If you are very conversant in react, you will know that usestate and useeffect are one of the most used React Hook.

What is a React Hook?

A React hook is a function that helps in making functions dynamic. This simply means when you want to make motions on a website then they are you go to-go. React Hooks are functions that react provides to help us complete various tasks. For example, toggling data or adding and removing data by simply clicking on a button. This will bring us to our next sub-heading: usestate() react hooks.

Digging deep into Usestate () React Hooks

Usestate() is a function, like we said above, coming from react. Usestate() allows you to add react state to functional components, allowing you to change their state. This simply means to use usestate() in your react app, you need to import it from the react library. It should be done like this:

import {useState} from 'React';

The usestate() react hook returns an array consisting of two values. The first one is the initial value while the second value is the function where you can change the value. Let us take a look:

const [value, setValue] = useState(initialState)

In the above code block, we just did a destructuring. If you do not understand destructuring, Click on me. The value is going to be the initial state while the setValue is a function used to change the initial state. P.s the second value should always be named starting with 'set'. Another thing to note when naming the second value, the function, is that after using 'set' add the name you used for the first value.For example, if you named the first value 'count' then the second value will 'setCount'.

Example 1:

Let us assume, we want to change a value when a button is clicked:

import {useState} from 'React';
const name = 'John';
function changeName () => {
const name = 'Mark';
console.log(name);
};
<button onClick={changeName}>Change name</button>

If name is console, it will be 'Mark' but when the button is clicked the name still remains as 'John'. Why could this be so?

This is because there is no where to preserve the previous state 'John'. To change the name by simply clicking on the button, follow this:

import {useState} from 'React';
const name = 'John';
function app() => {
const [value, setValue] = useState('John');
};
function changeName () => {
setValue('Mark');

};
<button onClick={changeName}>Change name</button>;

When the button is clicked on, the name will be changed from 'John' to 'Mark'.

CONCLUSION:

In conclusion, react hooks are relatively easy to use. It might look hard at first but constant use will lead to more understanding