- ReactJS Tutorial
- ReactJS - Home
- ReactJS - Introduction
- ReactJS - Installation
- ReactJS - Features
- ReactJS - Advantages & Disadvantages
- ReactJS - Architecture
- ReactJS - Creating a React Application
- ReactJS - JSX
- ReactJS - Components
- ReactJS - Nested Components
- ReactJS - Using Newly Created Components
- ReactJS - Component Collection
- ReactJS - Styling
- ReactJS - Properties (props)
- ReactJS - Creating Components using Properties
- ReactJS - props Validation
- ReactJS - Constructor
- ReactJS - Component Life Cycle
- ReactJS - Event management
- ReactJS - Creating an Event−Aware Component
- ReactJS - Introduce Events in Expense Manager APP
- ReactJS - State Management
- ReactJS - State Management API
- ReactJS - Stateless Component
- ReactJS - State Management Using React Hooks
- ReactJS - Component Life Cycle Using React Hooks
- ReactJS - Layout Component
- ReactJS - Pagination
- ReactJS - Material UI
- ReactJS - Http client programming
- ReactJS - Form Programming
- ReactJS - Controlled Component
- ReactJS - Uncontrolled Component
- ReactJS - Formik
- ReactJS - Conditional Rendering
- ReactJS - Lists
- ReactJS - Keys
- ReactJS - Routing
- ReactJS - Redux
- ReactJS - Animation
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - Table
- ReactJS - Managing State Using Flux
- ReactJS - Testing
- ReactJS - CLI Commands
- ReactJS - Building and Deployment
- ReactJS - Example
- Hooks
- ReactJS - Introduction to Hooks
- ReactJS - Using useState
- ReactJS - Using useEffect
- ReactJS - Using useContext
- ReactJS - Using useRef
- ReactJS - Using useReducer
- ReactJS - Using useCallback
- ReactJS - Using useMemo
- ReactJS - Custom Hooks
- ReactJS Advanced
- ReactJS - Accessibility
- ReactJS - Code Splitting
- ReactJS - Context
- ReactJS - Error Boundaries
- ReactJS - Forwarding Refs
- ReactJS - Fragments
- ReactJS - Higher Order Components
- ReactJS - Integrating With Other Libraries
- ReactJS - Optimizing Performance
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - React Without ES6 ECMAScript
- ReactJS - React Without JSX
- ReactJS - Reconciliation
- ReactJS - Refs and the DOM
- ReactJS - Render Props
- ReactJS - Static Type Checking
- ReactJS - Strict Mode
- ReactJS - Web Components
- Additional Concepts
- ReactJS - Date Picker
- ReactJS - Helmet
- ReactJS - Inline Style
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - Carousel
- ReactJS - Icons
- ReactJS - Form Components
- ReactJS - Reference API
- ReactJS Useful Resources
- ReactJS - Quick Guide
- ReactJS - Useful Resources
- ReactJS - Discussion
ReactJS - static getDerivedStateFromProps() Method
React is a well-known JavaScript library for creating user interfaces. There is a method in React called getDerivedStateFromProps that looks complicated, but let's break it down into simple words.
In React, getDerivedStateFromProps method is called just before the component renders, both when it first appears and when it updates. Its goal is to find out that the component's state needs to change in response to changes in its props.
Syntax
static getDerivedStateFromProps(props, state)
Parameters
props − The next set of props that the component will render with.
state − The state in which the component is about to render.
Return Value
If the state needs to be updated, it should return an object; otherwise, it should return null.
Examples
Example 1
Let's create a simple React app with the getDerivedStateFromProps function. In this example, we will create a form that automatically refreshes the email address when the user ID changes.
import React, { Component } from 'react'; class Form extends Component { state = { email: this.props.defaultEmail, prevUserID: this.props.userID }; static getDerivedStateFromProps(props, state) { if (props.userID !== state.prevUserID) { return { prevUserID: props.userID, email: props.defaultEmail }; } return null; } handleUserIDChange = (e) => { // Simulate user ID change this.props.onUserIDChange(e.target.value); }; handleEmailChange = (e) => { this.setState({ email: e.target.value }); }; render() { return ( <div> <label> User ID: <input type="text" value={this.props.userID} onChange={this.handleUserIDChange} /> </label> <br /> <label> Email: <input type="text" value={this.state.email} onChange={this.handleEmailChange} /> </label> </div> ); } } class App extends Component { state = { userID: '123', defaultEmail: 'user@example.com' }; handleUserIDChange = (newUserID) => { this.setState({ userID: newUserID }); }; render() { return ( <div> <h1>Form App</h1> <Form userID={this.state.userID} defaultEmail={this.state.defaultEmail} onUserIDChange={this.handleUserIDChange} /> </div> ); } } export default App;
Output
In the above example, The Form component has a user ID and an email input. When the user ID changes, the getDerivedStateFromProps function resets the email. The function handleUserIDChange simulates a user ID change. The App component sets the Form and manages changes to the user ID. This is a basic example, and we can change it to meet our specific requirements.
Example 2
Now we will create a simple counter app in which the initial count is given as a parameter and the counter can be incremented. When a prop changes, the getDerivedStateFromProps function is called to update the state.
import React, { Component } from 'react'; import './App.css'; class Counter extends Component { state = { count: this.props.initialCount, }; static getDerivedStateFromProps(props, state) { // Check if the initial count prop has changed if (props.initialCount !== state.count) { // Update the state with the new initial count return { count: props.initialCount, }; } return null; } handleIncrement = () => { this.setState((prevState) => ({ count: prevState.count + 1, })); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.handleIncrement}>Increment</button> </div> ); } } class App extends Component { state = { initialCount: 0, }; handleInitialCountChange = (e) => { const newInitialCount = parseInt(e.target.value, 10); this.setState({ initialCount: newInitialCount }); }; render() { return ( <div className='App'> <h1>Counter App</h1> <label> Initial Count: <input type="number" value={this.state.initialCount} onChange={this.handleInitialCountChange} /> </label> <Counter initialCount={this.state.initialCount} /> </div> ); } } export default App;
Output
Now, we have a simple React app in which the counter updates as per the initial count prop, and the getDerivedStateFromProps method is used to handle the prop changes.
Example 3
Let's create a simple React app that uses the lifecycle method getDerivedStateFromProps to display a message based on whether the user has logged in or not. So after running the app we will be able to see the message that the user is logged in or logged out.
import React, { Component } from 'react'; import './App.css'; class LoginStatus extends Component { static getDerivedStateFromProps(props, state) { // Check if the user is logged in const isLoggedIn = props.isLoggedIn; // Display different messages as per the login status return { statusMessage: isLoggedIn ? 'Welcome back! You are logged in.' : 'Please log in.' }; } render() { return ( <div> <p>{this.state.statusMessage}</p> </div> ); } } class App extends Component { state = { isLoggedIn: false }; handleLoginToggle = () => { this.setState((prevState) => ({ isLoggedIn: !prevState.isLoggedIn })); }; render() { return ( <div className='App'> <h1>Login App</h1> <button onClick={this.handleLoginToggle}> {this.state.isLoggedIn ? 'Logout' : 'Login'} </button> <LoginStatus isLoggedIn={this.state.isLoggedIn} /> </div> ); } } export default App;
Output
In the above app we have used getDerivedStateFromProps() method to check out the login and logout status of the user. As we can see in the above output there is a button shown on the screen when we click the button it will display the message “Welcome back! You are logged in.” And the button is changed to Logout.
Limitations
Unlike the former UNSAFE_componentWillReceiveProps, it is called on every render.
It does not have access to the component instance, therefore we cannot use it directly within it.
Summary
The getDerivedStateFromProps function can look difficult at first, but it is a tool for specific conditions. In basic terms, it allows us to manage the state of our component based on changes in its props.
To Continue Learning Please Login
Login with Google