Learn how to use the 'withState' and 'withHandlers' higher order components to easily add local state to—and create a reusable local state pattern for—your functional stateless components. No need for classes!
withState:
const Statue = withState('show', 'toggleShow', false)( ({ status, show, toggleShow }) => ( toggleShow((val) => !val)}> {status} {show && } ));
withState, we create a variable 'show' and a function 'toggleShow', the default value for 'show' is false. Now the variable and function are injected into our stateless component as props.
The function 'toggleShow' can just take a value as arguement or it can also take function as an arguement.
take as function:
onClick={() => toggleShow((val) => !val)}
take as value:
onClick={() => toggleShow(!show)}
withHandlers & compose:
To make withState more reuseable, we can use 'withHandler' & 'compose' to create an HoC.
const withToggle = compose( withState('toggleState', 'toggleShow', false), withHandlers({ toggle: ({toggleShow}) => (e) => toggleShow((val) => !val), show: ({toggleShow}) => (e) => toggleShow(true), hide: ({toggleShow}) => (e) => toggleShow(false) }));const Statue = withToggle( ({ status, toggle, toggleState }) => ( toggle(!toggleState)}> {status} {toggleState &&} ));const Tooltip = withToggle(({ show, hide, toggleState, text, children }) => ( {toggleState && { text }} { children } ));