Awesome work, we can now build “stateful” function components using the useState
React Hook!
Let’s review what we learned and practiced in this lesson:
With React, we feed static and dynamic data models to JSX to render a view to the screen
Use Hooks to “hook into” internal component state for managing dynamic data in function components
We employ the State Hook by using the code below:
currentState
to reference the current value of statestateSetter
to reference a function used to update the value of this statethe
initialState
argument to initialize the value of state for the component’s first renderconst [currentState, stateSetter] = useState( initialState );
Call state setters in event handlers
Define simple event handlers inline with our JSX event listeners and define complex event handlers outside of our JSX
Use a state setter callback function when our next value depends on our previous value
Use arrays and objects to organize and manage related data that tends to change together
Use the spread syntax on collections of dynamic data to copy the previous state into the next state like so:
setArrayState((prev) => [ ...prev ])
andsetObjectState((prev) => ({ ...prev }))
Split state into multiple, simpler variables instead of throwing it all into one state object
Instructions
Remember this class component from the beginning of this lesson? The same component was defined as a function component for your review, but at the time, a lot of that code probably didn’t make much sense! Not only would that code make sense to you if you had a look at it now, but after everything you’ve learned and practiced you can now write that code yourself!
Take a moment to read through this class component defined in the AppClass.js file, then switch over to the AppFunction.js file. Without any guidance, see if you can define a function component that behaves just like this class component, but saves us all of the complexity of dealing with JavaScript classes!
When you are ready to start testing your code, change the import statements in the index.js file, just like we did at the beginning of this lesson!
Good luck, we believe in you!