#TIL
I’m back, I’m back!
I finally graduated from the 10-week Nomad Coders Web Dev Basics sprint challenge, and am ready to move onwards to React. I learned React a few months ago earlier this year, but unfortunately didn’t do much with it beyond taking the Scrimba React course. Now that I’ve polished my JavaScript skills a bit more (I even finally finished created a Youtube-ish full-stack project with Node.js), I’m shifting gears to mastering React a bit more.
Components - Basically these lego blocks that are reusable.
- Looks like a function
const Header = () => {return (<header><h1>Hello, there!</h1><nav></nav></header>)
- Note the capitalized first letter of the Component
Props - looks very similar to HTML attributes that are placed within the component tag
- e.g.
<Header name="Boyeon" />
- When React sees these attribute-like pieces of information, it passes this to the component as a single OBJECT called props.
- Component functions can only have one parameter -> props. (e.g.
const Header = (props) => { return (<header><h1>Hello, there!</h1><nav></nav></header>)}
) - Cool thing I learned: You can access specific parts of the props individually by using destructuring code directly within the function:
//instead of
const Header = (props) => { return (<header><h1>Hello, there, {props.name}!</h1><nav></nav></header>)}
//you can also do
const Header = ({name}) => { return (<header><h1>Hello, there, {name}!</h1><nav></nav></header>)}
Nice thing about props? This is in my opinion what makes Components so reusable & flexible. If I want a certain set of buttons to have an identical UI, I can render them so easily using the <Btn />
component that has a certain set of styling already assigned, and then by passing the particular things I want to tailor via props.
Another quite important thing that I reviewed today:
- If you pass something like
onClick={clickHandler}
to a regular HTML element (e.g.<button onClick={clickHandler}></button>
in JSX you are essentially adding an eventlistener that listens to ‘click’. - However, if you are passing the same
onClick={clickHandler}
to your custom Component (e.g.<Button onClick={clickHandler} />
), you are not adding an event listener. Rather, you are passing a prop with the name ofonClick
. - If you do want to get a certain event handler from a parent and apply it to this
Rerender:
- When a parent component goes through a state change -> re-renders itself including the child components
- Even the child components that didn’t change also get rerendered according to this -> but if you don’t want a particular child component to be rerendered because the props haven’t changed for that component -> you caaaan use
React.Memo()
- To use
React.Memo()
, you basically pass the component as a parameter like so:MemorizedBtn = React.Memo(Button)