ReactJS Hooks: How to Use useState in ReactJS?



Hooks solve a wide variety of seemingly unconnected problems in React that we’ve encountered over five years of writing and maintaining tens of thousands of components. Whether you’re learning React, use it daily, or even prefer a different library with a similar component model, you might recognize some of these problems.

With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.

  • What is a Hook? A Hook is a special function that lets you “hook into” React features.
  • What is useState? useState is a Hook that lets you add React state to function components. We’ll learn other Hooks later.
  • When would I use a Hook? If you write a function component and realize you need to add some state to it.

useState
This is a kind of Hooks which is always used to give an initial state (the starting state) for your page preview without auto refresh page.

useState example as a Hook:
import { Button } from 'reactstrap';
import { useState } from 'react';

const HooksState = () => {
const [nama] = useState(['Jennie','Lisa','Rose','Jisoo']);
const [idx, setIdx] = useState(0);

const ubahNama = () => {
if(idx<nama.length-1) {
setIdx(idx+1);
console.log(idx);
} else {
setIdx(0);
console.log(idx);
}
}

return (
<>
<div className="App">
<h1 style={{
backgroundColor: '#D4EFDF'
}}>Hooks State Learning</h1>
<p>My Name: {nama[idx]}</p>
<Button color="primary" onClick={ubahNama}>Change the name</Button>
</div>
</>
)
}

export default HooksState;

Comments

Popular posts from this blog

How to Inspect Problems in Your ReactJS Codes