Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React functional component using state

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'};
like image 820
tmp dev Avatar asked Oct 19 '17 01:10

tmp dev


3 Answers

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

like image 78
Rafael Maldonado Avatar answered Oct 08 '22 18:10

Rafael Maldonado


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.

like image 45
Stephen Collins Avatar answered Oct 08 '22 18:10

Stephen Collins


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.

like image 40
Austin Greco Avatar answered Oct 08 '22 19:10

Austin Greco