Skip to content

Instantly share code, notes, and snippets.

@SirMoustache
Last active February 22, 2019 14:18
Show Gist options
  • Select an option

  • Save SirMoustache/f8f47bda7d8e10f8e9a1e4e146751991 to your computer and use it in GitHub Desktop.

Select an option

Save SirMoustache/f8f47bda7d8e10f8e9a1e4e146751991 to your computer and use it in GitHub Desktop.
React Hooks
import {useRef, useEffect} from 'react';
/**
* Hook for running effect on componentDidUpdate but not on componentDidMount
*/
const useComponentDidUpdate = (cb, dependencies) => {
const mounted = useRef(false)
useEffect(() => {
if (mounted.current) {
return cb()
}
mounted.current = true
}, dependencies)
}
import * as React from 'react';
import { func } from 'prop-types';
type ToggleRenderArgs = {
isOn: boolean;
handleOn: () => void;
handleOff: () => void;
};
export type ToggleRenderFunction = (args: ToggleRenderArgs) => JSX.Element;
export type ToggleProps = {
children?: React.ReactNode | ToggleRenderFunction;
render?: React.ReactNode | ToggleRenderFunction;
};
export default class Toggle extends React.Component<ToggleProps> {}
/**
* Absolute imports
*/
import { useState, useCallback } from 'react';
import PropTypes from 'prop-types';
const Toggle = ({ render, children }) => {
const [isOn, setIsOn] = useState(false);
const renderer = render || children;
const handleOn = useCallback(() => setIsOn(true), []);
const handleOff = useCallback(() => setIsOn(false), []);
return renderer({ isOn, handleOn, handleOff });
};
Toggle.propTypes = {
/**
* Render function that renders the actual component
*
* @param {Object} props
* @param {Boolean} props.isOn Returns state of toggle
* @param {Function} props.handleOn Set Toggle state to true
* @param {Function} props.handleOff Set Toggle state to false
*/
render: PropTypes.func,
/**
* Render function that renders the actual component
*
* @param {Object} props
* @param {Boolean} props.isOn Returns state of toggle
* @param {Function} props.handleOn Set Toggle state to true
* @param {Function} props.handleOff Set Toggle state to false
*/
children: PropTypes.func,
};
export default Toggle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment