question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Question about context

See original GitHub issue

Good day to you all. Im not sure this is actually an issue and my question is rather about best practices on your implementation of the context API.

I’m in a position where I’ve implemented it in a way that practically gives me access to a global context in all children’s lifecycles and rendering methods with either this.context or just the parameter ‘context’ in a stateless component. Since I haven’t seen this implementation anywhere else, I’m worried I might be adapting to a method that is some kind of anti-pattern or has risk of being dangerous. Being pretty green as I am, I thought I would just ask here for a more experienced perspective.

Basically, is there something really bad with this?

Thanks in advance, and please tell me if I’m posting this in the wrong place.

If you take a look at the following:

import { Component } from 'preact'

export default class BookmarkContext extends Component {
  state = {
		scrollTo: false,
    shouldHideOnScroll: true,
    scrollOffset: 0
	}
  
	getChildContext() {
		 return {
       state: this.state,
       setArticleScrollPos: this.setArticleScrollPos,
       resetScrollPos: this.resetScrollPos,
       setShouldHideOnScroll: this.setShouldHideOnScroll
     }
  }
  
  setShouldHideOnScroll = (scrollOffset, shouldHide) => this.setState({shouldHideOnScroll: shouldHide, scrollOffset: scrollOffset})
 
  setArticleScrollPos = data => {
    this.setState({scrollTo: data})
  }
  
  resetScrollPos = () => this.setState({scrollTo: false})

 
	render({ children }) {
		return <div>{children}</div>;
}
}

And then I wrap my whole application in this component in app.js:

render() {
		return (
			<MainContext>
				<ThemeProvider theme={ MainTheme }>
					<div>
						<Header init={this.state.init}/>
					<div id="app">
						<Router>
							<ArticlePreview initAudio={this.handleAudioInit} path="/"/>
							<ArticleBase path="article/:id"/>
							<ArticleBase path="article"/>
						</Router>
					</div>
				</div>
			</ThemeProvider>
		</MainContext>
		)
	}

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
marvinhagemeistercommented, Oct 9, 2018

This is a valid pattern for some apps. The only issue with that is that context updates may be blocked if there is as component somewhere in the tree which has the shouldComponentUpdate lifecycle.

This is solved via the new context api in react. We have not added it into core yet, but you can use the third party preact-context package instead. Another alternative are all the state management solutions out there like redux, mobx, unistore, unstated,…

0reactions
kumargauravincommented, Feb 14, 2022

so, We have SSR enabled app.

Context from react using a Reducer is exported from one TS file Imported in Index.tsx (SPA), gets FirstName property updated based on Rest API calls like based on some if-else. API can be different. Once we get Firstname, using React.context function, we update context value ( this is not happening as is ).

To resolve this issue, in Index.tsx page we added a state property for now and context seems to be working but not able to update value from a class component (as we have) using something like this.context.firstname = …

On Sun, Feb 13, 2022 at 10:29 AM Kumar Gaurav @.***> wrote:

Yes so in a class function, we are expecting React.Dispatch to update the value as is but until unless we add a state to the same object the value does not reflect in child object. Which makes me thing why state and context is to be used together.

I cannot share code here but will write some dummy code to illustrate the issue and solution we have put in place for now. Thanks for confirming this but.

On Sun, Feb 13, 2022 at 4:42 AM Marvin Hagemeister < @.***> wrote:

@kumargauravin https://github.com/kumargauravin Since Preact 10 we have full support for the newer createContext-API. It works 1:1 as it does in React.

I know it’s a closed issue, but now that preact has its own reducer and context, how I can replicate React’s reducer, context with a React.dispatch type of function, which can be used to update the context value from Class Components using dispatch.

I’m not entirely sure what you’re trying to do. For downstream components you’d just render a provider with the new context value. If you want to trigger an update higher up in the tree, the usual way is to pass an update function in the context value and that triggers an update in the desired parent.

— Reply to this email directly, view it on GitHub https://github.com/preactjs/preact/issues/1233#issuecomment-1037967597, or unsubscribe https://github.com/notifications/unsubscribe-auth/ADK64R3N5WZIKTVBLPRF4NLU254JFANCNFSM4F2JQ7EQ . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you were mentioned.Message ID: @.***>

– Regards, Kumar Gaurav +1 469 354 2101

– Regards, Kumar Gaurav +1 469 354 2101

Read more comments on GitHub >

github_iconTop Results From Across the Web

Question contexts - MoodleDocs
Question contexts are just as a subset of the Roles and Permissions contexts. A context contained by another context inherits the permissions of ......
Read more >
Asking Historical Context Questions - Christine Sleeter
Asking Historical Context Questions · What other socio-cultural groups were around (e.g., in the neighborhood, the town, the county)? · Who wasn't around...
Read more >
Context Clues Questions for Tests and Worksheets
You can create printable tests and worksheets from these Context Clues questions! Select one or more questions using the checkboxes above each question....
Read more >
''How to answer context questions in Literature'' by Anusha ...
''How to answer context questions in Literature'' by Anusha Thennakoon. 8.1K views 1 year ago. English Literature with Anusha Thennakoon.
Read more >
Ask about context before answering a question - Medium
In hindsight, I'd agree that the question could have been better phrased and with more context. But the author misunderstood what I was ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found