💡 Learn from AI

React Fundamentals

Props and State

Props and State

One of the fundamental concepts in React is the idea of props and state. Props are short for "properties" and they are used to pass data from one component to another. State, on the other hand, is used to manage data within a component.

Props

Props are passed to a component as an object of key-value pairs. These values can be anything from a string to a complex object. Once passed to a component, props are read-only and cannot be modified by the component. To access props within a component, you can use the props object.

Here's an example of a component that receives a name prop and displays it in a heading:

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

ReactDOM.render(
  <Greeting name="Alice" />, 
  document.getElementById('root')
);

State

State is used to manage data within a component that can change over time. Unlike props, state is mutable and can be modified by the component. To access state within a component, you can use the state object. To update state, you can use the setState method.

Here's an example of a component that uses state to keep track of a counter:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  incrementCount() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.incrementCount()}>Increment</button>
      </div>
    );
  }
}

ReactDOM.render(
  <Counter />, 
  document.getElementById('root')
);

Conclusion

Props and state are essential concepts in React that allow you to build dynamic and interactive user interfaces. By understanding the difference between props and state, you can write more efficient and effective React components.

Further Reading

  • React Documentation on Props and State

  • React Tutorial on Lifting State Up

Take quiz (4 questions)

Previous unit

React Components

Next unit

Handling Events in React

All courses were automatically generated using OpenAI's GPT-3. Your feedback helps us improve as we cannot manually review every course. Thank you!