FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

useMediatedState

20mins

Implement a function useMediatedState(mediator, initialState) that works like useState, but applies a mediator function whenever the state is updated.

The function should:

  • Accept an initial state value.
  • Accept a mediator function that can:
    • Transform the new state and return it: (newState) => newState
    • Or intercept the update using a dispatch function: (newState, dispatch) => void
  • Return an array containing:
    • The current state.
    • A setState function to update the state.

Example

const replaceMultipleSpaces = (s) => s.replace(/\s+/g, ' '); const [state, setState] = useMediatedState(replaceMultipleSpaces, ''); setState('hello world'); console.log(state); // 'hello world'

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests