score:3
useContext()
is only used to get your store value (reference) and this value is not updated frequently, usually you only set your stores once and don't touch it after. When you use actions you only change observable values of your store and not the store itself. So basically Context
is only used to pass reference to the store down the tree, after that all the work performed by MobX only.
Example from MobX docs:
import {observer} from 'mobx-react-lite'
import {createContext, useContext} from "react"
const TimerContext = createContext<Timer>()
const TimerView = observer(() => {
// Grab the timer from the context.
const timer = useContext(TimerContext) // See the Timer definition above.
return (
<span>Seconds passed: {timer.secondsPassed}</span>
)
})
ReactDOM.render(
<TimerContext.Provider value={new Timer()}
<TimerView />
</TimerContext.Provider>,
document.body
)
So you pass value of new Timer()
to TimerContext.Provider
once when you render your app and it will never be changed or updated after that. Even docs says:
Note that we don't recommend ever replacing the value of a Provider with a different one. Using MobX, there should be no need for that, since the observable that is shared can be updated itself.
However, if you don't have SSR or don't test your app, then you don't even need to use Context at all, you can just use global variables/singletons as your stores and it will work perfectly fine.
Example:
// Initialize timer somewhere
export const myTimer = new Timer()
// You can use directly in the same file or import somewhere else
import { myTimer } from './file-with-your-timer'
// No props, `myTimer` is directly consumed from the closure or from another file
const TimerView = observer(() => <span>Seconds passed: {myTimer.secondsPassed}</span>)
ReactDOM.render(<TimerView />, document.body)
Quote from docs:
Using observables directly works very well, but since this typically introduces module state, this pattern might complicate unit testing. Instead, we recommend using React Context instead.
More about best practices with React: https://mobx.js.org/react-integration.html
Source: stackoverflow.com
Related Query
- Shouldn't useContext() only be used for low frequent updates? (mobx-react-lite)
- React conditional render for logged in / logged out User only updates state with browser refresh
- react hooks useEffect() cleanup for only componentWillUnmount?
- React Router V6 - Error: useRoutes() may be used only in the context of a <Router> component
- const can only be used in a .ts file react native
- React batch updates for multiple setState() calls inside useEffect hook
- React show Material-UI Tooltip only for text that has ellipsis
- Can react js web code be used for building mobile apps using react native?
- React js: Error: useLocation() may be used only in the context of a <Router> component
- How to make React input onChange set state only after onChange stops firing for set time?
- How to toggle class for the only one element on click in react
- Why MobX is less suitable for applications that have an append only domain model?
- React Testing Library - "messageParent" can only be used inside a worker
- How can ı pass function with state for react useContext
- Only Display Component for Some Routes - React
- Prevent browser back button for a specific page only in react
- React Native only for UI components
- React Router V6 - useNavigate() may be used only in the context of a <Router> component
- React : How to display a modal popup only for that specific div
- React dangerouslySetInnerHTML Only working correctly when it is used on a div tag
- React constructor called only once for same component rendered twice
- What is dispatcherIndex used for in React TODO example
- How do I define a TypeScript type for React props where prop B is only accepted if prop A is passed to a component?
- Typescript for React createContext and useContext
- For loop only working on second loop with React hooks
- Do React state updates occur in order when used like an FSM and useEffect?
- Testing mobx react observer with react usecontext - React, Mobx
- Create a new MobX store instance for a React function component
- Can Firebase Emulators be used for integration testing with a React frontend?
- Percentage loading bar for React / Redux app like Pace.js that only shows on initial page load
More Query from same tag
- Uncaught (in promise) TypeError: Already read
- Where shoud I call Google map methods in my react app?
- React js filter selections
- Pass parameter to method in React
- How do I get the owner or parent of a react component
- Nested Routing in react-router-dom V5 not working
- TypeError: undefined is not an object (evaluating 'this.props.location') [ReactJS + react-router-dom V4]
- how to cancel web requests using interceptors?
- react input value needs to be set by useState hook in order to run onChange event but it's empty after I run a mutation
- Click icon button in the card component without clicking the whole card
- Material ui and reactjs, <Textfield/> with ref : doesn't work
- Best way to send data with React Router <Link>
- Validating File using React-Hook-Form and Yup (<x> must be a `object` type, but the final value was: `null`)
- Why not dispatch directly into store from action creator redux?
- How to send data from one react component to another react component?
- Unable to change y-axis value dynamically based on data for Stacked bar chart in reactjs
- Input Field Onchange not allowing to type
- Mapping through Strapi data doesnt work in React
- How to stop event from bubbling when exiting react-bootstrap modal?
- Calculating sum of array objects in javascript , TypeError: parseInt(...).reduce is not a function
- How to handle breadcrumbs?
- How to update react state twice in one submitHandler
- Nested TabNavigator inside StackNavigator: controlling the header
- Count views every time someone visit the page with firebase and Reactjs
- How to save multi-selected options into an array within React state
- TypeError: Cannot read property 'javascript' of undefined + terser webpack plugin + react js
- ES15 Import a library that is a plugin for another library
- React mui-datatables change header color
- react js conteneditable not working
- How to fire filter function that's set in a variable?