I Create Function Component In React And I Want to use state in it like class Component
-
funtion components are meant to be statelessSofiane Daoud– Sofiane Daoud2018-12-07 14:06:34 +00:00Commented Dec 7, 2018 at 14:06
-
With React 16.7 alpha this is not only possible but also encouraged because it can solve a entire set of issues bound to class components usage.Mosè Raguzzini– Mosè Raguzzini2018-12-07 14:31:30 +00:00Commented Dec 7, 2018 at 14:31
3 Answers
The only way you can use state in a component while not using an Alpha build of React, is by using a class component.
If you are happy to use an Alpha build of React then you can use React Hooks. React provides a function called useState which will allow you to do this.
https://reactjs.org/docs/hooks-overview.html
Do not use this in production while it's an alpha build. And be aware that while unlikely, the API can change significantly.
Comments
As React 16.7 alpha you actually CAN use state and effects to functional components through hooks:
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Although this is a new RFC, if you look at the Dan Abramov presentation (https://www.youtube.com/watch?v=dpw9EHDh2bM) you can deduce that is actually the future of react. And although React Blog states that classes won't be abandoned I bet that they will.
Notice also that hooks make state logic reusable between components without adding more components (like HoCs) to the application scaffolding.
Comments
If you want to use state or any lifecycle method you have to convert your functional component to class based component.
Class Components
Class-based Components uses ES6 class syntax. It can make use of the lifecycle methods.
As you can see in the example that u have given above Class components extend from React.Component.
In here you have to use this keyword to access the props and functions that you declare inside the class components.
Functional Components
Functional Components are simpler comparing to class-based functions.
Functional Components mainly focuses on the UI of the application, not on the behavior.
To be more precise these are basically render function in the class component.
Functional Components can't have state and they can't make use of lifecycle methods.