HOC

  • Higher Order Component
  • functions that take a component and return a new component with additional props or behavior
  • allow for code reuse and logic separation
function withLogging(WrappedComponent) {
  return function WithLogging(props) {
    useEffect(() => {
      console.log(`Component ${WrappedComponent.name} mounted`);
      return () => {
        console.log(`Component ${WrappedComponent.name} will unmount`);
      };
    }, []);
 
    return <WrappedComponent {...props} />;
  };
}
 
// ExampleComponent enhanced with withLogging HOC
function ExampleComponent() {
  return <div>Example Component</div>;
}
 
const ExampleWithLogging = withLogging(ExampleComponent);

Render props

  • technique where a component uses a prop with a function that returns a React element.
  • allows for dynamic and flexible code reuse.
function Toggle({ render }) {
  const [isOn, setIsOn] = useState(false);
 
  const toggle = () => {
    setIsOn((prevIsOn) => !prevIsOn);
  };
 
  return render({ isOn, toggle });
}
 
// ExampleComponent using Toggle
function ExampleComponent() {
  return (
    <Toggle
      render={({ isOn, toggle }) => (
        <div>
          <button onClick={toggle}>
            {isOn ? 'Turn off' : 'Turn on'}
          </button>
          {isOn && <p>The toggle is ON!</p>}
        </div>
      )}
    />
  );
}