Reactjs.org: Why are we putting function into component state?

Created on 22 May 2018  Â·  3Comments  Â·  Source: reactjs/reactjs.org

I'm trying to convince a friend of mine that he should only put serializable data types into React component state, then he gave me this link with an example of how Facebook add a function into component's state: https://reactjs.org/docs/context.html

This is the snippet:
context_-_react

Can someone help me to understand why we have to do this in the example code? Isn't it an anti-pattern?

Most helpful comment

I agree, there’s no such restriction. I think in general it’s not very common to need to put functions in state, and it’s often better to express data with plain objects instead of classic OOP models with methods, but there are cases when it’s useful. This is one of those cases.

All 3 comments

A context Provider can only pass its value prop to its Consumers. If you want your Consumers to be able to update the context value, you need to provide them with a mechanism to do that, and callback functions like toggleTheme do just that — the Consumer receives toggleTheme, and can call it to, well... toggle the theme.

Why is the Provider receiving the state object as its value? Because you _really_ don't want to create a new object each time it gets rendered, like it would happen if you did:

<ThemeContext.Provider value={ { theme: this.state.theme, toggleTheme: this.toggleTheme } }>

...as it would re-render all Consumers every time, even if the value has not deeply changed. State is a good place to keep the object you'll pass to the context provider.

I don't see a reason for a component's state to be serializable.

I agree, there’s no such restriction. I think in general it’s not very common to need to put functions in state, and it’s often better to express data with plain objects instead of classic OOP models with methods, but there are cases when it’s useful. This is one of those cases.

Thanks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

andresmatasuarez picture andresmatasuarez  Â·  5Comments

jaredp picture jaredp  Â·  4Comments

dstudzinski picture dstudzinski  Â·  3Comments

mbrowne picture mbrowne  Â·  5Comments

msert29 picture msert29  Â·  5Comments