React Stateful Components without classesConverting react class component to react stateless componentHow to change an element's class with JavaScript?$(document).ready equivalent without jQueryHow do I modify the URL without reloading the page?How can I select an element with multiple classes in jQuery?Loop inside React JSXWhat is the difference between state and props in React?Can you force a React component to rerender without calling setState?Programmatically navigate using react routerWhat is the appropiate way to define a react component class without state?How do react hooks determine the component that they are for?
What was the motivation for the invention of electric pianos?
Why is the T-1000 humanoid?
Why is the Digital 0 not 0V in computer systems?
How major are these paintwork & rust problems?
Some Prime Peerage
What explanation do proponents of a Scotland-NI bridge give for it breaking Brexit impasse?
I was promised a work PC but still awaiting approval 3 months later so using my own laptop - Is it fair to ask employer for laptop insurance?
What's 待ってるから mean?
Can I fix my boots by gluing the soles back on?
What exactly is a marshrutka (маршрутка)?
What jurisdiction do Scottish courts have over the Westminster parliament?
Why is this weapon searching for a new owner?
If the gambler's fallacy is false, how do notions of "expected number" of events work?
Can I tap all my opponent's lands while they're casting a spell to negate it?
Why did they ever make smaller than full-frame sensors?
Is "you will become a subject matter expert" code for "you'll be working on your own 100% of the time"?
Should you only use colons and periods in dialogues?
Were Roman public roads build by private companies?
Finding the number of digits of a given integer.
Planar regular languages
In Germany, how can I maximize the impact of my charitable donations?
Does an oscilloscope subtract voltages as phasors?
Should I leave the first authorship of our paper to the student who did the project whereas I solved it?
How can I discourage sharing internal API keys within a company?
React Stateful Components without classes
Converting react class component to react stateless componentHow to change an element's class with JavaScript?$(document).ready equivalent without jQueryHow do I modify the URL without reloading the page?How can I select an element with multiple classes in jQuery?Loop inside React JSXWhat is the difference between state and props in React?Can you force a React component to rerender without calling setState?Programmatically navigate using react routerWhat is the appropiate way to define a react component class without state?How do react hooks determine the component that they are for?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
In React, we can write components as pure functions. However, the problem with this is that you can't use it as stateful components because of the lack of lifecycle hooks and state. So, I wonder if is there any way to create stateful components without using classes.
Something that I found is the createClass
helper. But, React has moved this helper into their own package in the release 15.5.0
, link. Also, they recommend that you migrate them to JavaScript classes because classes are now the preferred way to create components in React. Therefore, I don't think that using this helper could be a good idea.
On the other hand, Facebook recommends the use of High Order Components (HOCs) which is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature. But, I couldn't find a way to create common stateful components without classes.
Has anyone gone through this? Is there any way to use React as a some purely functional solution?
javascript reactjs functional-programming
add a comment
|
In React, we can write components as pure functions. However, the problem with this is that you can't use it as stateful components because of the lack of lifecycle hooks and state. So, I wonder if is there any way to create stateful components without using classes.
Something that I found is the createClass
helper. But, React has moved this helper into their own package in the release 15.5.0
, link. Also, they recommend that you migrate them to JavaScript classes because classes are now the preferred way to create components in React. Therefore, I don't think that using this helper could be a good idea.
On the other hand, Facebook recommends the use of High Order Components (HOCs) which is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature. But, I couldn't find a way to create common stateful components without classes.
Has anyone gone through this? Is there any way to use React as a some purely functional solution?
javascript reactjs functional-programming
2
With monad's.
– Willem Van Onsem
Jul 30 '17 at 20:50
Do you have experience with any functional programming languages? You can simulate stateful operations using pure functions, you just need to return the new state as one of the return values, and then use that state as one of the parameters to the next time you call the function. The abstraction for this is called the "State monad".
– 4castle
Jul 30 '17 at 20:51
yes but what about react lifecycle hooks?
– mattias
Jul 30 '17 at 20:55
2
You can use lenses or cursors. This represents aget, set
pair of functions that can read and replace some subset of centralized state. One example of a library to help you implement this is omniscientjs.github.io
– Asad Saeeduddin
Jul 30 '17 at 21:19
Nice, didn't know about that. Btw, that library uses thecreateClass
helper also.
– mattias
Jul 30 '17 at 21:29
add a comment
|
In React, we can write components as pure functions. However, the problem with this is that you can't use it as stateful components because of the lack of lifecycle hooks and state. So, I wonder if is there any way to create stateful components without using classes.
Something that I found is the createClass
helper. But, React has moved this helper into their own package in the release 15.5.0
, link. Also, they recommend that you migrate them to JavaScript classes because classes are now the preferred way to create components in React. Therefore, I don't think that using this helper could be a good idea.
On the other hand, Facebook recommends the use of High Order Components (HOCs) which is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature. But, I couldn't find a way to create common stateful components without classes.
Has anyone gone through this? Is there any way to use React as a some purely functional solution?
javascript reactjs functional-programming
In React, we can write components as pure functions. However, the problem with this is that you can't use it as stateful components because of the lack of lifecycle hooks and state. So, I wonder if is there any way to create stateful components without using classes.
Something that I found is the createClass
helper. But, React has moved this helper into their own package in the release 15.5.0
, link. Also, they recommend that you migrate them to JavaScript classes because classes are now the preferred way to create components in React. Therefore, I don't think that using this helper could be a good idea.
On the other hand, Facebook recommends the use of High Order Components (HOCs) which is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature. But, I couldn't find a way to create common stateful components without classes.
Has anyone gone through this? Is there any way to use React as a some purely functional solution?
javascript reactjs functional-programming
javascript reactjs functional-programming
edited Jul 30 '17 at 21:12
mattias
asked Jul 30 '17 at 20:48
mattiasmattias
8789 silver badges22 bronze badges
8789 silver badges22 bronze badges
2
With monad's.
– Willem Van Onsem
Jul 30 '17 at 20:50
Do you have experience with any functional programming languages? You can simulate stateful operations using pure functions, you just need to return the new state as one of the return values, and then use that state as one of the parameters to the next time you call the function. The abstraction for this is called the "State monad".
– 4castle
Jul 30 '17 at 20:51
yes but what about react lifecycle hooks?
– mattias
Jul 30 '17 at 20:55
2
You can use lenses or cursors. This represents aget, set
pair of functions that can read and replace some subset of centralized state. One example of a library to help you implement this is omniscientjs.github.io
– Asad Saeeduddin
Jul 30 '17 at 21:19
Nice, didn't know about that. Btw, that library uses thecreateClass
helper also.
– mattias
Jul 30 '17 at 21:29
add a comment
|
2
With monad's.
– Willem Van Onsem
Jul 30 '17 at 20:50
Do you have experience with any functional programming languages? You can simulate stateful operations using pure functions, you just need to return the new state as one of the return values, and then use that state as one of the parameters to the next time you call the function. The abstraction for this is called the "State monad".
– 4castle
Jul 30 '17 at 20:51
yes but what about react lifecycle hooks?
– mattias
Jul 30 '17 at 20:55
2
You can use lenses or cursors. This represents aget, set
pair of functions that can read and replace some subset of centralized state. One example of a library to help you implement this is omniscientjs.github.io
– Asad Saeeduddin
Jul 30 '17 at 21:19
Nice, didn't know about that. Btw, that library uses thecreateClass
helper also.
– mattias
Jul 30 '17 at 21:29
2
2
With monad's.
– Willem Van Onsem
Jul 30 '17 at 20:50
With monad's.
– Willem Van Onsem
Jul 30 '17 at 20:50
Do you have experience with any functional programming languages? You can simulate stateful operations using pure functions, you just need to return the new state as one of the return values, and then use that state as one of the parameters to the next time you call the function. The abstraction for this is called the "State monad".
– 4castle
Jul 30 '17 at 20:51
Do you have experience with any functional programming languages? You can simulate stateful operations using pure functions, you just need to return the new state as one of the return values, and then use that state as one of the parameters to the next time you call the function. The abstraction for this is called the "State monad".
– 4castle
Jul 30 '17 at 20:51
yes but what about react lifecycle hooks?
– mattias
Jul 30 '17 at 20:55
yes but what about react lifecycle hooks?
– mattias
Jul 30 '17 at 20:55
2
2
You can use lenses or cursors. This represents a
get, set
pair of functions that can read and replace some subset of centralized state. One example of a library to help you implement this is omniscientjs.github.io– Asad Saeeduddin
Jul 30 '17 at 21:19
You can use lenses or cursors. This represents a
get, set
pair of functions that can read and replace some subset of centralized state. One example of a library to help you implement this is omniscientjs.github.io– Asad Saeeduddin
Jul 30 '17 at 21:19
Nice, didn't know about that. Btw, that library uses the
createClass
helper also.– mattias
Jul 30 '17 at 21:29
Nice, didn't know about that. Btw, that library uses the
createClass
helper also.– mattias
Jul 30 '17 at 21:29
add a comment
|
4 Answers
4
active
oldest
votes
Writing Stateful component without using classes is definitely a choice made by several developers. I recommend to use 'recompose' which has nice and easy implementation to write stateful components without class, yet apply state, both local and from store. Here is an example:
import compose from 'recompose/compose'
import withState from 'recompose/withState'
import withProps from 'recompose/withProps'
Pure.js
function MyComponent(props) (
local: prop1, prop2 ,
setProp1
)
return <div>prop1</div>
}
const defaultState =
prop1: false,
prop2: false
const enhance = compose(
withState('local', 'updateLocal', defaultState),
withProps(( local: prop1, prop2 , updateLocal ) => (
setProp1: (newValue) => updateLocal(state => (...state, prop1: newValue ))
)))
export default enhance(MyComponent)
Where has this library been all my life.
– Asad Saeeduddin
Jul 31 '17 at 5:36
Thanks! what about react lifecycle hooks? Can you use it?
– mattias
Aug 1 '17 at 18:59
@mattias, I am not sure that lifecycle events can be attached too. So far I haven't seen that implemented. You might want to visit recompose library for more details.
– Umesh
Aug 2 '17 at 2:57
add a comment
|
A new feature supports this, called React hooks. From the documentation:
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
A simple example:
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>
);
For an example of how to use lifecycles, check out useEffect
It's not experimental anymore so you might want to update your answer
– vsync
Mar 25 at 10:20
Thanks for the feedback, updated
– Karamell
Mar 25 at 13:09
Note that React16.8
is out and has hooks support
– vsync
Mar 25 at 13:40
Yes, updated now again :)
– Karamell
Mar 28 at 10:26
You'll have to update it again in a year, removing the word "new" ;)
– vsync
Mar 28 at 13:07
|
show 1 more comment
Maybe react-instance can become handy. Take a look at examples below.
Save state in local variable:
import React from "react"
import instance from "react-instance"
const App = instance(( forceUpdate ) =>
let time = 0
const timer = setInterval(() =>
time++
forceUpdate()
, 100)
return
render()
return time
,
unmount()
clearInterval(timer)
,
)
Save state in component state:
import React from "react"
import instance from "react-instance"
const App = instance(instance =>
instance.state = time: 0
const timer = setInterval(() =>
instance.setState( time: instance.state.time + 1 )
, 100)
return
render()
return instance.state.time
,
unmount()
clearInterval(timer)
,
)
add a comment
|
I tried to create a simple stateful component named Comp without the usage of es6 classes.
Here is the code
Basically I'm linking the prototype of the Comp function (our stateful component) to the prototype object of React.Component and I pass down to it Comp's props to initialize it properly. After that you can use every function of the React.Component object on the Comp.prototype. I used some just an example. I don't know if this is the best way in the "most javascript" way to use react
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45404546%2freact-stateful-components-without-classes%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Writing Stateful component without using classes is definitely a choice made by several developers. I recommend to use 'recompose' which has nice and easy implementation to write stateful components without class, yet apply state, both local and from store. Here is an example:
import compose from 'recompose/compose'
import withState from 'recompose/withState'
import withProps from 'recompose/withProps'
Pure.js
function MyComponent(props) (
local: prop1, prop2 ,
setProp1
)
return <div>prop1</div>
}
const defaultState =
prop1: false,
prop2: false
const enhance = compose(
withState('local', 'updateLocal', defaultState),
withProps(( local: prop1, prop2 , updateLocal ) => (
setProp1: (newValue) => updateLocal(state => (...state, prop1: newValue ))
)))
export default enhance(MyComponent)
Where has this library been all my life.
– Asad Saeeduddin
Jul 31 '17 at 5:36
Thanks! what about react lifecycle hooks? Can you use it?
– mattias
Aug 1 '17 at 18:59
@mattias, I am not sure that lifecycle events can be attached too. So far I haven't seen that implemented. You might want to visit recompose library for more details.
– Umesh
Aug 2 '17 at 2:57
add a comment
|
Writing Stateful component without using classes is definitely a choice made by several developers. I recommend to use 'recompose' which has nice and easy implementation to write stateful components without class, yet apply state, both local and from store. Here is an example:
import compose from 'recompose/compose'
import withState from 'recompose/withState'
import withProps from 'recompose/withProps'
Pure.js
function MyComponent(props) (
local: prop1, prop2 ,
setProp1
)
return <div>prop1</div>
}
const defaultState =
prop1: false,
prop2: false
const enhance = compose(
withState('local', 'updateLocal', defaultState),
withProps(( local: prop1, prop2 , updateLocal ) => (
setProp1: (newValue) => updateLocal(state => (...state, prop1: newValue ))
)))
export default enhance(MyComponent)
Where has this library been all my life.
– Asad Saeeduddin
Jul 31 '17 at 5:36
Thanks! what about react lifecycle hooks? Can you use it?
– mattias
Aug 1 '17 at 18:59
@mattias, I am not sure that lifecycle events can be attached too. So far I haven't seen that implemented. You might want to visit recompose library for more details.
– Umesh
Aug 2 '17 at 2:57
add a comment
|
Writing Stateful component without using classes is definitely a choice made by several developers. I recommend to use 'recompose' which has nice and easy implementation to write stateful components without class, yet apply state, both local and from store. Here is an example:
import compose from 'recompose/compose'
import withState from 'recompose/withState'
import withProps from 'recompose/withProps'
Pure.js
function MyComponent(props) (
local: prop1, prop2 ,
setProp1
)
return <div>prop1</div>
}
const defaultState =
prop1: false,
prop2: false
const enhance = compose(
withState('local', 'updateLocal', defaultState),
withProps(( local: prop1, prop2 , updateLocal ) => (
setProp1: (newValue) => updateLocal(state => (...state, prop1: newValue ))
)))
export default enhance(MyComponent)
Writing Stateful component without using classes is definitely a choice made by several developers. I recommend to use 'recompose' which has nice and easy implementation to write stateful components without class, yet apply state, both local and from store. Here is an example:
import compose from 'recompose/compose'
import withState from 'recompose/withState'
import withProps from 'recompose/withProps'
Pure.js
function MyComponent(props) (
local: prop1, prop2 ,
setProp1
)
return <div>prop1</div>
}
const defaultState =
prop1: false,
prop2: false
const enhance = compose(
withState('local', 'updateLocal', defaultState),
withProps(( local: prop1, prop2 , updateLocal ) => (
setProp1: (newValue) => updateLocal(state => (...state, prop1: newValue ))
)))
export default enhance(MyComponent)
answered Jul 31 '17 at 3:09
UmeshUmesh
2,13714 silver badges19 bronze badges
2,13714 silver badges19 bronze badges
Where has this library been all my life.
– Asad Saeeduddin
Jul 31 '17 at 5:36
Thanks! what about react lifecycle hooks? Can you use it?
– mattias
Aug 1 '17 at 18:59
@mattias, I am not sure that lifecycle events can be attached too. So far I haven't seen that implemented. You might want to visit recompose library for more details.
– Umesh
Aug 2 '17 at 2:57
add a comment
|
Where has this library been all my life.
– Asad Saeeduddin
Jul 31 '17 at 5:36
Thanks! what about react lifecycle hooks? Can you use it?
– mattias
Aug 1 '17 at 18:59
@mattias, I am not sure that lifecycle events can be attached too. So far I haven't seen that implemented. You might want to visit recompose library for more details.
– Umesh
Aug 2 '17 at 2:57
Where has this library been all my life.
– Asad Saeeduddin
Jul 31 '17 at 5:36
Where has this library been all my life.
– Asad Saeeduddin
Jul 31 '17 at 5:36
Thanks! what about react lifecycle hooks? Can you use it?
– mattias
Aug 1 '17 at 18:59
Thanks! what about react lifecycle hooks? Can you use it?
– mattias
Aug 1 '17 at 18:59
@mattias, I am not sure that lifecycle events can be attached too. So far I haven't seen that implemented. You might want to visit recompose library for more details.
– Umesh
Aug 2 '17 at 2:57
@mattias, I am not sure that lifecycle events can be attached too. So far I haven't seen that implemented. You might want to visit recompose library for more details.
– Umesh
Aug 2 '17 at 2:57
add a comment
|
A new feature supports this, called React hooks. From the documentation:
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
A simple example:
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>
);
For an example of how to use lifecycles, check out useEffect
It's not experimental anymore so you might want to update your answer
– vsync
Mar 25 at 10:20
Thanks for the feedback, updated
– Karamell
Mar 25 at 13:09
Note that React16.8
is out and has hooks support
– vsync
Mar 25 at 13:40
Yes, updated now again :)
– Karamell
Mar 28 at 10:26
You'll have to update it again in a year, removing the word "new" ;)
– vsync
Mar 28 at 13:07
|
show 1 more comment
A new feature supports this, called React hooks. From the documentation:
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
A simple example:
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>
);
For an example of how to use lifecycles, check out useEffect
It's not experimental anymore so you might want to update your answer
– vsync
Mar 25 at 10:20
Thanks for the feedback, updated
– Karamell
Mar 25 at 13:09
Note that React16.8
is out and has hooks support
– vsync
Mar 25 at 13:40
Yes, updated now again :)
– Karamell
Mar 28 at 10:26
You'll have to update it again in a year, removing the word "new" ;)
– vsync
Mar 28 at 13:07
|
show 1 more comment
A new feature supports this, called React hooks. From the documentation:
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
A simple example:
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>
);
For an example of how to use lifecycles, check out useEffect
A new feature supports this, called React hooks. From the documentation:
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
A simple example:
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>
);
For an example of how to use lifecycles, check out useEffect
edited Mar 28 at 10:26
answered Nov 4 '18 at 8:06
KaramellKaramell
6604 silver badges17 bronze badges
6604 silver badges17 bronze badges
It's not experimental anymore so you might want to update your answer
– vsync
Mar 25 at 10:20
Thanks for the feedback, updated
– Karamell
Mar 25 at 13:09
Note that React16.8
is out and has hooks support
– vsync
Mar 25 at 13:40
Yes, updated now again :)
– Karamell
Mar 28 at 10:26
You'll have to update it again in a year, removing the word "new" ;)
– vsync
Mar 28 at 13:07
|
show 1 more comment
It's not experimental anymore so you might want to update your answer
– vsync
Mar 25 at 10:20
Thanks for the feedback, updated
– Karamell
Mar 25 at 13:09
Note that React16.8
is out and has hooks support
– vsync
Mar 25 at 13:40
Yes, updated now again :)
– Karamell
Mar 28 at 10:26
You'll have to update it again in a year, removing the word "new" ;)
– vsync
Mar 28 at 13:07
It's not experimental anymore so you might want to update your answer
– vsync
Mar 25 at 10:20
It's not experimental anymore so you might want to update your answer
– vsync
Mar 25 at 10:20
Thanks for the feedback, updated
– Karamell
Mar 25 at 13:09
Thanks for the feedback, updated
– Karamell
Mar 25 at 13:09
Note that React
16.8
is out and has hooks support– vsync
Mar 25 at 13:40
Note that React
16.8
is out and has hooks support– vsync
Mar 25 at 13:40
Yes, updated now again :)
– Karamell
Mar 28 at 10:26
Yes, updated now again :)
– Karamell
Mar 28 at 10:26
You'll have to update it again in a year, removing the word "new" ;)
– vsync
Mar 28 at 13:07
You'll have to update it again in a year, removing the word "new" ;)
– vsync
Mar 28 at 13:07
|
show 1 more comment
Maybe react-instance can become handy. Take a look at examples below.
Save state in local variable:
import React from "react"
import instance from "react-instance"
const App = instance(( forceUpdate ) =>
let time = 0
const timer = setInterval(() =>
time++
forceUpdate()
, 100)
return
render()
return time
,
unmount()
clearInterval(timer)
,
)
Save state in component state:
import React from "react"
import instance from "react-instance"
const App = instance(instance =>
instance.state = time: 0
const timer = setInterval(() =>
instance.setState( time: instance.state.time + 1 )
, 100)
return
render()
return instance.state.time
,
unmount()
clearInterval(timer)
,
)
add a comment
|
Maybe react-instance can become handy. Take a look at examples below.
Save state in local variable:
import React from "react"
import instance from "react-instance"
const App = instance(( forceUpdate ) =>
let time = 0
const timer = setInterval(() =>
time++
forceUpdate()
, 100)
return
render()
return time
,
unmount()
clearInterval(timer)
,
)
Save state in component state:
import React from "react"
import instance from "react-instance"
const App = instance(instance =>
instance.state = time: 0
const timer = setInterval(() =>
instance.setState( time: instance.state.time + 1 )
, 100)
return
render()
return instance.state.time
,
unmount()
clearInterval(timer)
,
)
add a comment
|
Maybe react-instance can become handy. Take a look at examples below.
Save state in local variable:
import React from "react"
import instance from "react-instance"
const App = instance(( forceUpdate ) =>
let time = 0
const timer = setInterval(() =>
time++
forceUpdate()
, 100)
return
render()
return time
,
unmount()
clearInterval(timer)
,
)
Save state in component state:
import React from "react"
import instance from "react-instance"
const App = instance(instance =>
instance.state = time: 0
const timer = setInterval(() =>
instance.setState( time: instance.state.time + 1 )
, 100)
return
render()
return instance.state.time
,
unmount()
clearInterval(timer)
,
)
Maybe react-instance can become handy. Take a look at examples below.
Save state in local variable:
import React from "react"
import instance from "react-instance"
const App = instance(( forceUpdate ) =>
let time = 0
const timer = setInterval(() =>
time++
forceUpdate()
, 100)
return
render()
return time
,
unmount()
clearInterval(timer)
,
)
Save state in component state:
import React from "react"
import instance from "react-instance"
const App = instance(instance =>
instance.state = time: 0
const timer = setInterval(() =>
instance.setState( time: instance.state.time + 1 )
, 100)
return
render()
return instance.state.time
,
unmount()
clearInterval(timer)
,
)
answered Apr 20 '18 at 18:47
pravdomilpravdomil
2,10615 silver badges32 bronze badges
2,10615 silver badges32 bronze badges
add a comment
|
add a comment
|
I tried to create a simple stateful component named Comp without the usage of es6 classes.
Here is the code
Basically I'm linking the prototype of the Comp function (our stateful component) to the prototype object of React.Component and I pass down to it Comp's props to initialize it properly. After that you can use every function of the React.Component object on the Comp.prototype. I used some just an example. I don't know if this is the best way in the "most javascript" way to use react
add a comment
|
I tried to create a simple stateful component named Comp without the usage of es6 classes.
Here is the code
Basically I'm linking the prototype of the Comp function (our stateful component) to the prototype object of React.Component and I pass down to it Comp's props to initialize it properly. After that you can use every function of the React.Component object on the Comp.prototype. I used some just an example. I don't know if this is the best way in the "most javascript" way to use react
add a comment
|
I tried to create a simple stateful component named Comp without the usage of es6 classes.
Here is the code
Basically I'm linking the prototype of the Comp function (our stateful component) to the prototype object of React.Component and I pass down to it Comp's props to initialize it properly. After that you can use every function of the React.Component object on the Comp.prototype. I used some just an example. I don't know if this is the best way in the "most javascript" way to use react
I tried to create a simple stateful component named Comp without the usage of es6 classes.
Here is the code
Basically I'm linking the prototype of the Comp function (our stateful component) to the prototype object of React.Component and I pass down to it Comp's props to initialize it properly. After that you can use every function of the React.Component object on the Comp.prototype. I used some just an example. I don't know if this is the best way in the "most javascript" way to use react
answered Nov 23 '18 at 9:53
Alpe89Alpe89
1831 silver badge9 bronze badges
1831 silver badge9 bronze badges
add a comment
|
add a comment
|
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45404546%2freact-stateful-components-without-classes%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
With monad's.
– Willem Van Onsem
Jul 30 '17 at 20:50
Do you have experience with any functional programming languages? You can simulate stateful operations using pure functions, you just need to return the new state as one of the return values, and then use that state as one of the parameters to the next time you call the function. The abstraction for this is called the "State monad".
– 4castle
Jul 30 '17 at 20:51
yes but what about react lifecycle hooks?
– mattias
Jul 30 '17 at 20:55
2
You can use lenses or cursors. This represents a
get, set
pair of functions that can read and replace some subset of centralized state. One example of a library to help you implement this is omniscientjs.github.io– Asad Saeeduddin
Jul 30 '17 at 21:19
Nice, didn't know about that. Btw, that library uses the
createClass
helper also.– mattias
Jul 30 '17 at 21:29