The app is now finished - check it out here: https://www.monicaspastrycakes.com/
This post is about React hooks, particularly the state hook, and how it was used in my recent project.
React Hooks
What is a hook?
If you write a function and realize you need to add some state to it, you have to convert it to a class. React hooks save the trouble of this implementation change by allowing you to simply "hook into" the existing function. Let's see how this is done with the state hook.
How I used the state hook in my app
My application required customers to select options to personalize their orders. In order to do this, I used a variable called productDetails which had child attributes such as flavor, shape, and description. Attributes of productDetails needed to be set dynamically - every time a customer selects something for their desired product. The example below shows how I accomplished this:
State hook example
First, we import the useState method with:
import React, { useState } from 'react'
Next, we define the variable whose state will be updated. We pass initial values for each attribute to the useState method, as so:
const [state, setState] = useState({initial value})
Example from my project:
![](https://static.wixstatic.com/media/c37be2_1ac666bacbac4bc395671753f59ddfbd~mv2.jpg/v1/fill/w_781,h_37,al_c,q_80,enc_avif,quality_auto/c37be2_1ac666bacbac4bc395671753f59ddfbd~mv2.jpg)
Now we can call setState to 'update' the state of our variable, as so:
setState({ ...state, state.attribute: attribute_value })
Code walkthrough from my project:
Flavor function
Each flavor is mapped to a picture of the flavor.
Each picture is displayed in a carousel with a caption of the flavor.
When the picture or caption is clicked or selected, we call the PickFlavor.
PickFlavor function
Set the flavor attribute of the productDetails variable by calling setProductDetails.
If the caption (<p> element) is clicked, pass in the innerHTML.
If the picture is clicked, pass in the alt text of the image.
Lastly, a notification pops up to the user.
![](https://static.wixstatic.com/media/c37be2_927abe99e44d4c46962e05b5c7a3b2ba~mv2.jpg/v1/fill/w_471,h_466,al_c,q_80,enc_avif,quality_auto/c37be2_927abe99e44d4c46962e05b5c7a3b2ba~mv2.jpg)
Output:
![](https://static.wixstatic.com/media/c37be2_aa4bf420253b47128a4a9485f8b4aeb8~mv2.gif/v1/fill/w_980,h_444,al_c,usm_0.66_1.00_0.01,pstr/c37be2_aa4bf420253b47128a4a9485f8b4aeb8~mv2.gif)
Comentarios