Components
Class vs Function
Class
Your class needs to extend React.Component
and must implement the render
function, which returns the representation of the component.
External props
can be access via this.props
.
If you want your component to manage state, then you have to use the state
property.
import React from 'react';
export default class StatefulComponent extends React.Component {
constructor (props) {
super(props);
this.state = {
counter: 0
}
}
render() {
return (<div>Counter: { this.state.counter }</div>);
}
}
Function
The anatomy of a functional component is a lot simpler, as it just returns its representation with the return
statement.
External props
get passed as function argument and can be accessed via props
.
If you want your component to manage state, then you have to use the useState
hook.
import React, {useState} from 'react';
export default function StatefulComponent(props) {
const [value, setValue] = useState({ counter: 0 });
return (<div>Counter: { this.state.counter }</div>);
}
Controlled vs Uncontrolled
This is relevant for HTML elements the user can interact with, e.g. an input or a select-box.
The difference is as follows:
- Uncontrolled: If a component reads its state from the DOM, here you would work with
useRef
to access and update the state - Controlled: If a component reads its state exclusively from "within", e.g. it manages its own state via
useState
oruseReducer