React Navigation 5: Dynamic header title (with hooks)

Last updated on March 19, 2021 A Goodman Loading... 2 comments

This article shows you how to dynamically update the header title of a screen in a React Native app. We will use React Native latest version, the useState hook, the useEffect hook, and the React Navigation 5 library.

This is what you will see when running the final code:

Let’s jump into the code

Create a brand new React Native app by running:

npx react-native init test_app

Install the required packages:

npm i @react-navigation/native react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view @react-navigation/stack

Install the pods (if you are using macOS):

npx pod-install ios

Replace all the default code in App.js with the snippet below:

import 'react-native-gesture-handler';

import React from 'react';
import {NavigationContainer} from '@react-navigation/native';

import MainNavigator from './src/navigations/MainNavigator';

function App() {
  return (
      <MainNavigator />

export default App;

Create a new folder called src. It will contain all the code we write a few seconds later (this isn’t what you must do but it help keep the code clean).

mkdir src

In the src folder, create navigations and screens folders. Inside these ones, create MainNavigator.js and FirstScreen.js.

├── navigations
│   └── MainNavigator.js
└── screens
    ├── FirstScreen.js


import React from 'react';
import {createStackNavigator} from '@react-navigation/stack';

import FirstScreen from '../screens/FirstScreen';

const MainStack = createStackNavigator();

const MainNavigator = props => {
  return (
      <MainStack.Screen name="first" component={FirstScreen} />

export default MainNavigator;


import React, {useState, useEffect} from 'react';
import {View, StyleSheet, TextInput} from 'react-native';

const FirstScreen = props => {
  const [headerTitle, setHeaderTitle] = useState('Default Title');

  // Rerender after headerTitle change
  useEffect(() => {
      title: headerTitle,
  }, [headerTitle, props.navigation]);

  // the function that handle the onChangeText event of the TextInput
  const updateTitle = enteredValue => {

  return (
    <View style={styles.screen}>

/// Just some styles
const styles = StyleSheet.create({
  screen: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  textInput: {
    padding: 10,
    width: 300,
    borderColor: '#666',
    borderWidth: 1,

export default FirstScreen;

That’s all. Now run your app and try typing something in the text box.

Notify of
Inline Feedbacks
View all comments
8 months ago

Thank you very much!!

React Navigation 5: useRoute hook example | Kindacode
1 year ago

[…] See also: How to dynamically set the header title when using React Navigation 5 […]

Related Articles