React is a:
JavaScript library for building user interfaces.
import React from "react";
import ReactDOM from "react-dom";
class Greetings extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
ReactDOM.render(
<Greetings name={"Kenneth McCormick"} />,
document.getElementById("root")
);
Components let you split the UI into
and think about each piece in isolation.
React lets you define components as classes or functions.
constructor(props)
render()
Should return:
It should be pure, predictable, and it does not interact directly with the browser.
componentDidMount() {
// Logic goes here
}
After all the elements of the page is rendered correctly, this method is called.
This method is the perfect place to fetch data from an API endpoint and then call setState to re-render component with updated data.
componentDidUpdate(prevState, prevProps) {
// Logic goes here
}
This method is called when a component got updated. This might happen if new props have been provided by a parent component or an internal state has been changed.
The componentDidUpdate function receives previous props and state as parameters.
shouldComponentUpdate(nextProps, nextState) {
// Logic goes here
}
shouldComponentUpdate function is being called before an update
componentWillUnmount() {
// Logic goes here
}
componentWillUnmount is the last function to be called immediately before the component is removed from the DOM.
PureComponent is exactly the same as Component except that it handles the shouldComponentUpdate method for you.
When props or state changes, PureComponent will do a shallow comparison on both props and state.
A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element.
No setState(), no lifecycle methods... no happiness, no life....
No setState(), no lifecycle methods... no happiness, no life....
A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element.
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
Hooks let you "hook into" the underlying lifecycle and state changes of a component within a functional component. More than that, they often also improve readability and organization of your components
useState is used to handle state in a functional component.
import React, { useState } from 'react';
function CountApp() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect adds the ability to perform side effects from a function component.
import React, { useState } from 'react';
function ChatApp() {
useEffect(() => {
// login and fetch messages
// (componentDidMount and/or componentDidUpdate)
return () => {
// logout (componentWillUnmount)
};
}, [ /* properties to watch */]);
return (
<></>
);
}