React js State Example (2024) | TechGeekNext


React js State Example (2024)

What is Reactjs?

React is a component-based library that breaks down the user interface into smaller, reusable components. In some circumstances, those components will need to communicate (give data to one another), and the best method to do so is to use props.

What is State in ReactJS?

The state is a built-in React object that holds data or information about the component. The state of a component can change depending upon the user actions on the components or with any system events.

What is State Hooks in ReactJS?

In React 16.8, hooks are a new feature to use state. They allow you to use React's state and other capabilities without having to write a class. Backwards compatibility exists with hooks.

Reactjs Dependencies

Add below dependencies in package.json file.

{
  "name": "reactjs-state-example",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

React Hooks State

Below are basic steps required to use react hooks state.

  1. Import the function useState from the React library. useState is a so-called React hook ,there are other hooks as well,
    import React, { useState } from 'react';

    And all these React hooks can be recognized by the fact that they start with the word use in their name.

  2. We will call the function on any action event or change event to set the new values.
    <button onClick={buttonClickHandler}>Update Values</button>
  3. Ues the react hooks useState with two variables i.e actual value and values to be updated.
    const [name, setName] = useState(props.name);
  4. Function to set the new value.
     const buttonClickHandler = () => {
            setName('XYZ');
            console.log(name);
          };

Take a look at our suggested post :

ReactJS Hooks State Implementation

Project Structure - Reactjs useState()

React State

App.js

Update the App.js with following code.

import './App.css';
import './components/EmployeeItems'
import EmployeeItems from './components/EmployeeItems';

function App() {

  return (
    <div><h2>TechGeekNext State Tutorial</h2>
    <EmployeeItems
    id='1'
    name='TechGeekNext User1'
    role='Admin'>
    </EmployeeItems>
    </div>
  );
}

export default App;

Use React Hooks useState()

Create EmployeeItems.js in the src/components folder. Import useState hooks from the React Library to change the values on the button click.

import React, { useState } from 'react';
import './style.css'
function EmployeeItems(props){
    const [name, setName] = useState(props.name);
    const [role, setRole] = useState(props.role);


    const buttonClickHandler = () => {
        setName('XYZ');
        setRole('User');
        console.log(name);
      };


    return(
        <div>
        <div className='employee-item__table'>
        <div>{props.id}</div>
        <div>{name}</div>
        <div>{role}</div>
        </div>
        <button onClick={buttonClickHandler}>Update Values</button>
        </div>
    );
}
export default EmployeeItems;

Test the Reactjs Hooks state

  • Use below command to install all the dependencies required for the project.
    npm install
  • Run the application by using below command:
    npm start
  • By default application will open in browser at http://localhost:3000/ url. React State
  • If we click on the button, it will change the values of user and role. React State







  • Recommendation for Top Popular Post :