...

/

Balancing Global Information and Synchronization

Balancing Global Information and Synchronization

Learn about the versatility of the useRef hook in React.

Optimizing global data sync

When we design a web application, we tend not to have a global variable, because we know it's so easy that their usage can lead to some unmanageable side effects. On the other hand, if we have some global information that is valid for the entire site, it's still handy if we want to share it with the rest of the app behind the scenes. So, what kind of compromise can we have in this situation?

When we create a context to share info for a site. We can provide the information at the very top of the tree, the App component:

const App = () => {
// Use the useState hook to manage a state variable 'value'
const [value, setValue] = useState(0);
// Render the AppContext.Provider, providing 'value' and 'setValue' to its children
return (
<AppContext.Provider value={{ value, setValue }}>
...
</AppContext.Provider>
);
}
Setting up AppContext's values

A fact of using the state in the preceding code is that when changing a value through the setValue dispatch function, it causes the whole site to update, which can be a very expensive operation.

Efficient state management with useRef

If we don't need to notify the user of this change, we ...