A Simple Approach to Handling State in React.


This week was all about using react hooks to get manage the state of my pages and get them talking to each other. I’ll dive right into it! So what is state? State is a very general way to reference how data and or properties of a page might change over time. One of the simplest examples that can be used to illustrate this is a user entering data into an initially empty form field. The act of entering the data (and hitting submit in this case) changes the state of the given page where the form is located. As you can imagine this is something that might be pretty useful to track. Enter the useState react hook! This useful tool allows us to monitor and record changes to state. See the syntax below

Here, useState is initialized with a default value as it’s argument and the return value from the useState is destructured into a variable to track and a set function that will be used to actually update the state. Then what we can do attach the setter function to an event listener like onChange in our form so that when the field is changed useState can call the setter to store the new value. As a side note we can use the default value used as a useState() input parameter to populate the form with data from a prop passed to the component. As seen below.

One more useful hook that I want to cover is the useNavigation hook. This hook can do quite a bit from looking at the documentation, but I used to it allow a click event to load a new page. I wanted to accomplish two things, have the edit button in my table open my edit page, and also pass the edit page the data in the row the button is located on. To do this with this hook required a few things to be done. First is to declare the hook and used it in a function. Inside the function I need to specify what page managed by the router I want it to navigate to, and what props to pass to that page. Then in my dynamically generated table I need to pass the edit function and apply it to each row inside the button component. All of this is illustrated below.

Thanks for tuning in this week. I know I said that I would have all my stuff integrated into our backend this week but we ran into some blockers so I focused on getting all my pages linked and working instead.

Sources:

  1. https://www.w3schools.com/react/react_usestate.asp
Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *