Setting State in a Functional Component

An introduction to React Hooks

While learning to write components in React the decision that seemed to always come up was whether that component should be a Functional or a Class component. As a new React developer i always leaned towards making my components for the most part Class components, due to the fact that class components gave you more flexibility when it came to logic. When i would consider writing a functional component the main question that came to mind was ..

  • Where and how do I set State?

Luckily for new React Developers ,React has created functions called HOOKS that let you pass State and other Properties into a Functional Component. Hooks allow you to use React without having to write Class Components.

Setting State using Hooks

The first step to setting state in a functional component is by importing the useState hook from React as seen down below.

import React, { useState } from 'react'

Now that we have imported our useState hook, we can use the useState hook to set state in our Functional Component .The useState hook is used to manage a component’s state and keep it it between re-renders. The way you can implement the useState hook is by including a pair of variables – one to represent the actual starting state of your component and the other representing what you want your component’s state to be updated to.

In the example down below we have a shareButton Functional Component , the useState hook is used to set the state of the button to “originalButtonState” which is rendering the string of “Click to Share this Post” on the button.

import React, { useState } from "react";function shareButton() {
const [originalButtonState, clickedButtonState] = useState("Click to Share this Post");

An onClick is set to that button and will change the text of the button to the updated state of the button “clickedButtonState” which then changes the text of the button to “Thanks for Sharing!”

function handleClick() {
return clickedButtonState("Thanks for Sharing!");
}
return <button onClick={handleClick}>{originalButtonState}</button>;
}

The useState Hook makes functional components seem a-lot more appealing , it gives you the ability to write less code, dryer code and still have the functionality of setting state!

Full-Stack Software Engineer / New York City / www.danielcreyes.dev