DEV Community

Adrian0506
Adrian0506

Posted on

React Hooks

React hooks are a pretty amazing tool in Javascript. You can easily change a components state without making it a class. It is fairly simple and easy to use. It saves a lot of time and you can use them multiple times in a single component.
I will show you a example of how react hooks will look.

import React, {useState} from 'react';

function App () {
let [currentCount, incrementCount] = useState(0);

return <>

Click Me

{currentCount}

</>

}

This small function basically creates a variable with a value of 0. When you click on click me it increments the count. Which will change that variables state. This will cause the page to re render to show the correct count. I like using hooks because I believe it makes code look cleaner, you also have to write less lines of code to change the state. I feel like this is fairly popular among developers.

Also some examples can be maybe you want to render something based if the state is true or false, with useState it is basically works as a toggle. When you click something you can toggle it to be true and then when you click it again you can toggle it to be off. If you want more complex states you may have to use a class component in order to pull it off.

Top comments (0)