Skip to content

Instantly share code, notes, and snippets.

@scwood
Created July 12, 2022 19:25
Show Gist options
  • Save scwood/42ae0209484ed3c790f1e5465f78c5c5 to your computer and use it in GitHub Desktop.
Save scwood/42ae0209484ed3c790f1e5465f78c5c5 to your computer and use it in GitHub Desktop.
React context example for sharing audio player controls
// AudioControlsProvider.tsx
import { createContext, useState, ReactNode, useContext } from 'react';
// This is the interface of our context object, i.e. this is the interface of
// stuff that normal components will have access to
export interface AudioControls {
isAudioPlaying: boolean;
pauseAudio: () => void;
}
// This doesn't really matter, we'll never end up using these defaults but when
// you create a context you must provide default values
const defaultContextValue: AudioControls = { isAudioPlaying: false, pauseAudio: () => {} };
const AudioControlsContext = createContext<AudioControls>(defaultContextValue);
export function AudioControlsProvider(props: { children: ReactNode }) {
const [isAudioPlaying, setIsAudioPlaying] = useState(false);
function pauseAudio() {
setIsAudioPlaying(false);
}
return (
<AudioControlsContext.Provider value={{ isAudioPlaying, pauseAudio }}>
{props.children}
</AudioControlsContext.Provider>
);
}
export function useAudioControls() {
return useContext(AudioControlsContext);
}
// App.tsx
export function App() {
return (
<AudioControlsProvider>
{/* The rest of your app goes here, or at least everything that will need access to the audio controls. */}
</AudioControlsProvider>
);
}
// AudioPlayer.tsx
export function AudioPlayer() {
const { isAudioPlaying, pauseAudio } = useAudioControls();
return <div>{/* Use the values from the hook in your audio player. */}</div>;
}
// VideoPlayer.tsx
export function VideoPlayer() {
const { pauseAudio } = useAudioControls();
function playVideo() {
pauseAudio();
// The rest of the code to play video
}
return <div>{/* etc... */}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment