Câu hỏi phỏng vấn React Native
Câu hỏi

How are props and state different?

Câu trả lời

In React Native, both props and state are essential concepts for managing data and controlling the behavior of components. However, they serve different purposes and have distinct characteristics. Here is a detailed comparison:

Props

  1. Definition: Props, short for properties, are used to pass data from a parent component to a child component. They are similar to function arguments in that they allow you to pass values from one component to another.
  2. Immutability: Props are immutable, meaning that once they are set by the parent component, they cannot be changed by the child component. This ensures predictable behavior of components[1][2][3][4][5].
  3. Usage: Props are primarily used to configure child components and pass data and callback functions to them. They enable a unidirectional data flow, where the parent dictates the values and behavior of the child component[3][5][6].
  4. Component Re-rendering: A component will re-render when its props change, ensuring that the component's UI stays consistent with the data it receives[3][4].
  5. Example:
    function ChildComponent(props) {
      return <div>{props.message}</div>;
    }
    
    function ParentComponent() {
      return <ChildComponent message="Hello, World!" />;
    }

State

  1. Definition: State is a built-in object in a React component where you can store property values that belong to that component. It is used to store local and temporary data that might change over time[1][2][3][4][5].
  2. Mutability: Unlike props, state is mutable. This means that it can be changed, and when it does change, the component re-renders to reflect those changes[1][2][3][4][5].
  3. Usage: State is used to manage data that is specific to a component and can't be computed from props. It is ideal for handling user interactions, form inputs, and other dynamic data that affects the component's behavior or appearance[2][3][4][5].
  4. Component Re-rendering: A component will re-render when its local state changes, allowing for dynamic behavior in response to data changes or user interactions[3][4].
  5. Example:
    import React, { useState } from 'react';
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      function handleClick() {
        setCount(count + 1);

...

middle

middle

Gợi ý câu hỏi phỏng vấn

junior

Why do we use curly brace while importing some library?

middle

What happens if you edit a module that only exports React components in Fast Refresh?

expert

Does React Native have a Virtual DOM?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào