I'm trying to implement a React smart component using functions as shown here https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc
My problem is however that I need to maintain state, and how do I do it in this scenario, for example I need to access and set
this.state = {Title: 'Login'};
From React 16.8.0 You can use Hooks using useState
to instantiate a State custom in your Functional Component. Like This...
import React, {useState} from 'react';
const AddButon = ({handleAddValue}) => {
return <button onClick={handleAddValue}>Add</button>
}
const App = (props) =>{
const [value, setValue] = useState(0);
const handleAddValue = () => {
const newValue = value+1;
setValue(newValue);
}
return (
<div>
<div>The Value is: {value}</div>
<AddButon handleAddValue={handleAddValue} />
</div>);
}
If you want to read more about this new functionality, follow the following link.
https://reactjs.org/docs/hooks-intro.html
Stateless functional components are intended to be presentation-oriented, since they can't have local UI state within themselves. This is great though, because without the ability to have internal state, the use of pure functional components promotes better use of the single responsibility principle through out your app, allowing simpler components each focused on doing less stuff. A win for designing software that becomes less of a headache to maintain and add features to later.
Stateless functional components are passed in state from a Container component and are responsible for rendering the state passed in to them via props from their Container component. This allows the Container component to have a simpler, more focused responsibility for getting and transforming data to pass to the stateless functional components. The pure functional components abstract out the details of rendering JSX from the Container.
So long story, what you want is a container component class so you have can create relevant UI state and manage it in the React lifecycle methods, which you do not have access to in a pure functional component.
Update: As of React 16.8.0, this is no longer true. See Rafael Moldonado's answer above
Stateless Functional Components can't have state, you will need to use a regular React Component if you want to have state within the component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With