State & Props

1. Understanding Through Examples

State

  • Values that can change 'inside' the component during component usage

  • ex) age, address, employment status

Props

  • Values received from 'external' sources

  • ex) name, gender

2. Characteristics of Props

Component Properties

  • (Unchanging) properties that the component has in web applications

Values Received from Parent Component

  • React components are JavaScript functions and classes

  • Receive props like function arguments β†’ return React elements that describe how to display on screen based on this

  • Therefore, can be used as initial values containing data to be output on screen when the component is first rendered

Object Form

  • Can pass any type of value

Read-Only

  • Read-only objects that cannot be changed arbitrarily

  • If not read-only, could affect values of parent components that passed props

  • Also violates unintended side effects or React's unidirectional/downward data flow principle

3. How to Use Props

Define Values and Properties to Pass to Child Components

Pass Defined Values and Properties Using Props

Render Received Props

Props Children

There's also a method to pass values by putting them between opening and closing tags

4. State Hook, useState

How to Use useState and How It Works

useState Pseudocode

useState Syntax Example

JSX Ternary Operator Usage Example

5. Updating State

  • To update, call setIsChecked which is a function that can update state variables

  • When user changes checkbox value, onchange event calls event handler function handleChecked, and this function calls setIsChecked

  • When setIsChecked is called, isChecked variable is updated according to result

  • React passes new isChecked variable to CheckboxExample component, re-rendering that component

6. Points to Note

  • React components are newly called and re-rendered when state changes

  • React state must be changed by calling state update functions, cannot be forcibly changed

7. Event Handling

  • In React, events use camelCase

  • Use JSX to pass event handling functions (event handlers) as functions, not strings

onChange

onClick

Event used when application should react according to user actions like button clicks or link navigation through <a> tags

Last updated