My Development Notes

Programming Made Easier


React State : Basics with Real World Examples

React State is actually an object with encapsulated data which changes in response to instructions given to it using event listeners and handlers.

For example, clicking the ‘add item’ button should take you to a screen where the item is added to a shopping cart, or clicking the ‘next page’ link should take you to the next page of a website.

Example

Let’s see how it actually works with this example :

import { useState } from "react";
// import useState from React
import { basicInfo } from "./Page";
import "./App.css";

function BirdDetails() {
  const [index, setIndex] = useState(0);

  function onClicking() {
    setIndex(index + 1);
  }

  let webPage = basicInfo[index];
  return (
    <>
      <h2>{webPage.name}</h2>
      <img src={webPage.imgFile} />
      <p>{webPage.details}</p>
      <button onClick={onClicking}>Next Page</button>
    </>
  );
}

export default BirdDetails;
import img1 from "./Images/image1.jpg";
import img2 from "./Images/image2.png";
import img3 from "./Images/image3.jpg";
// imported images from 'Images' component

export const basicInfo = [
  {
    name: "First Image",
    details:
      "This is a very beautifully taken photograph of a bird found in the junges of North America.",
    imgFile: img1,
  },
  {
    name: "Second Image",
    details:
      "This image was created by an artist and it looks so elegent and beautiful. The design is perfect.",
    imgFile: img2,
  },
  {
    name: "Third Image",
    details:
      "This image is that of a mother duck and its children freely swimming across the river ",
    imgFile: img3,
  },
];

Output :

When you click on the ‘Next Page’ button it switches to the alternate images.

Explanation

In the Page.js file, first we’ve created an object wherein we’ve created three card like pages (which are just key-value pairs in reality) with three parameters like name, details and the images.

Then inside the App.js file we’ve added a state variable using the useState hook.

Here in const [index, setIndex] = useState(0), index is the state variable. Also setIndex is the setter function which runs when onClicking function gets executed on clicking the button and gets incremented by ‘1’ each time. This switches the pages.

Note : On clicking the ‘Next Page’ button third time an error will show up because this is just the basics and we didn’t loop through the button as of now. You can use the refresh button to go back.

Why is useState used with React State Variable?

const [stateVariable, stateSetterFunction] = useState(0); 

State variable is the initial value you store while state setter function updates the variable and triggers a response like ‘next one or plus one’ in our case.

useState is called to make the component remember something. In our example it wants you to remember the index value of ‘0’ by default i.e., the first page.


Posted

in

by

Leave a Reply