Controlled vs Uncontrolled
All Mantine inputs support both controlled and uncontrolled modes. This guide explains the difference between these two modes and when to use each of them.
Controlled components
A controlled component is a form element whose value is stored in React state.
The value is passed with the value prop and updated in the onChange handler.
Example of a controlled TextInput component:
Every keystroke triggers a state update, which causes a re-render with the new value.
Uncontrolled components
An uncontrolled component manages its own state through the DOM or internal state, similar to regular HTML form elements. Use refs or DOM methods to read the current value when needed, usually on form submission.
Example of an uncontrolled TextInput component:
Key differences
- Controlled components store state in React, uncontrolled components store it in the DOM
- Controlled components use
valueprop, uncontrolled components usedefaultValue - Controlled components require
onChangehandler to remain interactive, uncontrolled components work without change handlers, like regular HTML inputs
When to use which
Use controlled components when:
- You need to validate or manipulate input values in real-time.
- You want to enforce specific formats or constraints on user input.
- You require immediate feedback or dynamic UI updates based on input changes.
Use uncontrolled components when:
- You want to simplify your code and reduce boilerplate for simple forms.
- You don't need to validate or manipulate input values until form submission.
- You are working with large forms where performance is a concern, and you want to minimize re-renders.
FormData and uncontrolled components
Uncontrolled forms are often used with the FormData API,
which allows you to easily collect form values without managing state for each input. All Mantine components
support uncontrolled usage with FormData.
Example of using uncontrolled Checkbox with FormData:
Uncontrolled use-form
@mantine/form supports uncontrolled mode. Use it to build large forms with many fields without re-rendering the form on every change.
Example of uncontrolled mode with useForm: