Props vs State in React

Props vs State in React

Props and states can be confusing when learning React. What's the difference between them? When should you use props, and when should you use states? In this article, we will explore these questions and, hopefully, clear up the confusion.

Props

Props (short for properties) are like special inputs passed into components. They allow a component to access and use customized data and values.

Consider this example:

// App.jsx
import Button from './Button';

const App = () => {
    return(
        <div>
            <h1>Welcome User</h1>
            <Button />
        </div>
    );
}

export default App;
// Button.jsx
const Button = () => {
  const handleSignup = () => {
    console.log("Signup button clicked");
  };

  return <button onClick={handleSignup}>Sign Up</button>;
}

export default Button;

The example above currently only creates a sign-up button. But what if we wanted to create a login button too? We could make a separate button component just for login, but that would mean repeating a lot of code. Instead, let's create a reusable Button component that can handle both!

// App.jsx
import Button from './Button';

const App = () => {
  const handleSignup = () => {
    console.log("Signup button clicked");
  };

  const handleLogin = () => {
    console.log("Login button clicked");
  };

  return (
    <div>
      <h1>Welcome User</h1>
      <Button text="signup" handleClick={handleSignup} />
      <Button text="login" handleClick={handleLogin} />
    </div>
  );
}

export default App;
// Button.jsx
const Button = (props) => {
  return <button onClick={props.handleClick}>{props.text}</button>;
}

export default Button;

The approach above demonstrates how to use props. By using props, the information in the App component can be passed down to the Button component, thus making the Button component reusable.

Let's simplify the Button component and avoid using the props keyword.

// Button.jsx
const Button = ({text, handleClick }) => {
  return <button onClick={handleClick}>{text}</button>;
}

export default Button;

State

In the example above, our application is static, meaning the result is always the same. But what if we want things to change? That's where state comes in.

Let's consider this example:

// App.jsx
const App = () => {
    const [isChecked, setIsChecked] = useState(false);

    return (
        <div className='App'>
         <p>Are you sure you want to continue?</p>
         <form>
            <label htmlFor="confirm-checkbox">
               <input
                 id="confirm-checkbox"
                 type="checkbox"
                 checked={isChecked}
                 onChange={() => setIsChecked(!isChecked)}
               />
               <span>I agree with the terms and conditions.</span>
            </label>
            <button>{isChecked ? "Confirm" : "Cancel"}</button>
         </form>
        </div>
}

export default App;

The isChecked state tracks changes as the user toggles the checkbox between true and false. This also affects the text shown on the button. It's important to note that states are not global, so isChecked can only be accessed within its current component. To pass the isChecked state to another component, you would use props.

// App.jsx
import Button from './Button';

const App = () => {
    const [isChecked, setIsChecked] = useState(false);

    return (
        <div className='App'>
         <p>Are you sure you want to continue?</p>
         <form>
            <label htmlFor="confirm-checkbox">
               <input
                 id="confirm-checkbox"
                 type="checkbox"
                 checked={isChecked}
                 onChange={() => setIsChecked(!isChecked)}
               />
               <span>I agree with the terms and conditions.</span>
            </label>
            <Button isChecked={isChecked} />
         </form>
        </div>
}

export default App;
// Button.jsx
const Button = ({isChecked}) => {
  return(
    <button>{isChecked ? "Confirm" : "Cancel"}</button>
  )
}

export default Button;

Differences between State and Props

  • State:

    • Managed within the component where it is created using the useState hook.

    • Can be changed by the component where it is initialized.

    • Used for dynamic data that changes over time, such as handling user input.

    • Not accessible outside the component unless passed down as props.

  • Props:

    • Passed from parent to child components.

    • Cannot be changed by the receiving or child component.

    • Used to pass data and event handlers to child components.

    • Helps in making components reusable by allowing them to receive different data.

Conclusion

Props and state serve different purposes in React. Props are used to pass data from parent to child components, while state is used to handle dynamic data and user interactions. Props are immutable in the receiving components, while state can be modified within the component where it is initialized. If state needs to be used in another component, it needs to be passed as a prop. Understanding their differences helps in effectively managing and organizing React applications.