Props and State in React
--
Mad props to the folks who create this awesome open-source, front-end, JS Library known as React. React is great for single-page apps, rendering Data to the DOM, routing, and state management. I find it helpful to simplify over-complicated terms and break them down, so in case you’re just starting out I hope you find these bullets helpful.
Props
What the heck are Props?
Properties aka Props
Props
allow us to send data through components making them dynamic and reusable- The values sent through
props
can be strings, functions, arrays, and objects Props
are Read-OnlyProps
are immutable FANCY FOR unable to change- Can only be passed from Parent to Child.
How to use Props:
- Define
props
in component’s JSX tag - Take in and use
props
in a component
What we are doing in the App component is sending down a prop
called name with the value of “Kelsey” to the Greeting component.
import React from 'react';const Greeting = (props) => { return(
<h1>Hi {props.name}</h1>
)}
export default Greeting
Now the Greeting component has access to props! Inside our curly braces in JSX we have access to the value of name and can render to the screen.
Output:
State
What the heck is State?
- Is a POJO (Plain Ole JavaScript Object)
- The
state
object can contain as many properties as you like state
holds the initial information- Once the
state
changes the component re-renders - If you update
state,
you should not modify directly, but instead, usesetState()
Where does State live?
State
can live in both class and functional components. However, if you choose to use a functional component, you will need to use React’s Hooks.
Here is an example of a functional component using hooks:
The output from code above:
Now, this is a class component using state:
As you can immediately see, code with hooks is much shorter syntax. Both options allow you to manage your state
locally but cannot be accessed or modified outside of the component unless passing as props
. While state
increases complexity, it is good practice to have fewer stateful components, allowing for easier state
management.
Props vs State
While props
and state
have their differences, they do share some commonalities.
- Both are POJO’s (Plain Ole JavaScript Objects)
- Both trigger a render update
- Both can contain default values
The difference between state
and props:
Summary
Props
and state
are both important fundamental concepts in React. In my opinion, React is a wonderful library filled with magic for the developer to implement and the User to experience. If at first, it seems overwhelming and hard, just know, it does get better. Practice makes perfect!