React.js state and props

React is a popular JavaScript library for building user interfaces. It allows developers to create reusable UI components that manage their own state and accept props from their parent components. In this article, we will explore the concepts of state and props in React.js.

State in React.js

State is a built-in feature in React that represents the current state of a component. It is an object that can be accessed and updated within a component. State is used to store and manage data that can change over time.

To define and use state in a React component, you need to use the useState hook. Here’s an example that shows how to create and use state in a functional component:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  }

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;

In the above example, we define a state variable count and a function setCount to update its value. We use the useState hook to initialize the state to 0. When the “Increment” button is clicked, the increment function is called, which updates the state and triggers a re-render of the component.

Props in React.js

Props are read-only data that are passed from parent components to child components. They allow you to pass data and function references down through the component hierarchy. Props are used to customize and configure child components based on the parent’s requirements.

Here’s an example that demonstrates how to use props in a React component:

import React from 'react';

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

export default Greeting;

In the above code, the Greeting component accepts a name prop from its parent component. The props object contains all the passed props as key-value pairs. We access the name prop using props.name and display it in the rendered component.

To use the Greeting component, you can pass the name prop like this:

import React from 'react';
import Greeting from './Greeting';

function App() {
  return <Greeting name="John" />;
}

export default App;

In the App component, we render the Greeting component and pass the name prop with the value “John”. This will result in the rendered text “Hello, John!”.

Conclusion

Understanding and effectively using state and props in React.js is crucial for building dynamic and interactive user interfaces. State allows components to manage their own data, while props enable communication and customization between parent and child components. By harnessing the power of state and props, you can create more flexible and reusable React components.

#Reactjs #stateandprops