Reputation: 8108
So I decided to use ImmutableJS for working with Redux. Now I am wondering if it is convenient to use it for managing React Component state
. I coded the following:
class Navigation extends React.Component {
constructor(props) {
super(props);
const $$fixedLinks = Immutable.fromJS(this.props.fixedLinks);
const $$dynamicLinks = Immutable.fromJS(this.props.dynamicLinks);
this.state = {
fixedLinks: this.addHrefs($$fixedLinks),
dynamicLinks: this.addHrefs($$dynamicLinks),
};
}
// Given a list of shape (id, name) we need to
// add href for the links
addHrefs = list => list.map(item => item.set('href', toUnderscore(item.get('name'))))
render() {
const fixed = this.state.fixedLinks.map(
link => (
<Link key={link.get('id')} href={`#${link.get('href')}`} title={link.get('name')} />
),
);
const dynamic = this.state.dynamicLinks.map(
link => (
<Link key={link.get('id')} href={`#${link.get('href')}`} title={link.get('name')} />
),
);
return (
<Anchor>
{fixed}
{dynamic}
</Anchor>
);
}
}
As you can see $$
indicates an immutable object. But then I want to add a new property to it with addHrefs
and save it to state
.
It is working like a charm. But it is a little akward the following:
<Link key={link.get('id')} href={`#${link.get('href')}`} title={link.get('name')} />
see? Using get()
for getting values from the immutable object.
Now, some questions:
ImmutableJS
for managing
state in React.Component
?ImmutableJS
for this purpose, should this.state
be
an immutable object? if so, how to deal with this.setState()
?loadash
because it won't work with
ImmutableJS
, how can I deal with immutable states inside
React.Component
?Upvotes: 1
Views: 433
Reputation: 4097
- Is it a good idea (or approach) to use
ImmutableJS
for managing state inReact.Component
?
I can't see why it would be a bad idea. It's even mentioned in React docs.
- If I can use
ImmutableJS
for this purpose, shouldthis.state
be an immutable object? if so, how to deal withthis.setState()
?
That's really up to you. There are benefits for having component state to be immutable (like being able to use PureComponent
and get optimized performance).
I'm not sure what you mean with "deal with this.setState()
". You continue to use it as usual: fetch your state, update it (thus obtaining a new object), call setState
with the new object.
- If not so, I can't use
loadash
because it won't work withImmutableJS
, how can I deal with immutable states insideReact.Component
?
You can call const myState = this.state.toJS()
and use lodash with it. Just don't try to change the component's state changing something in myState
because that won't work.
I hope this answers your questions, if I understood them correctly :)
Upvotes: 2