ReactJS Refs Last Updated : 09 Jan, 2025 Comments Improve Suggest changes Like Article Like Report ReactJS Refs are used to access and modify the DOM elements in the React Application. It creates a reference to the elements and uses it to modify them.Table of ContentCreating refs in ReactAccessing Refs in ReactWhy useRef over createRef in Function Components?When to use refsWhen not to use refsWhat is Refs in React?Refs are a function provided by React to access the DOM element and the React elements created in components. They are used in cases where we want to change the value of a child component, without making use of props and state. They allow us to interact with these elements outside the typical rendering workflow of React.They have wide functionality as we can use callbacks with them. Creating refs in ReactReactJS Refs can be created using React.createRef() function and attached to a React element via the ref attribute.When a class component is constructed, the Refs are commonly assigned to an instance property so that they can be referenced in the component.Exampleclass MyComponent extends React.Component { constructor(props) { super(props); this.myCallRef = React.createRef(); } render() { return <div ref={this.myCallRef} />; }}Detailed guide on How to create refs in React JS?Accessing Refs in ReactIn React, when a ref is passed to an element in render using the ref attribute, the underlying DOM element or React component becomes accessible at the current property of the ref.const node = this.myCallRef.current;Now, we are going to see how we can use refs in our code which will help you to understand the use case of refs better.ExampleIn this example, we use the target value of event e, for getting the value. JavaScript // Filename - App.js // without refs class App extends React.Component { constructor() { super(); this.state = { sayings: "" }; } update(e) { this.setState({ sayings: e.target.value }); } render() { return ( <div> Mukul Says{" "} <input type="text" onChange={this.update.bind(this)} /> <br /> <em>{this.state.sayings}</em> </div> ); } } ReactDOM.render(<App />, document.getElementById("root")); Output: Refs Current PropertiesThe current property value of refs depends on the ref target. Look at the table below, to understand the difference.Target Typecurrent Property ValueHTML elementDOM element objectCustom React component (class component)React component instanceMore Examples of Refs in ReactLet's look at some of the React code examples of refs. The examples will provide a better learning experience for master ReactJS refs.Example 1: In this example, we use refs to add a callback function indirectly with the help of the update function and onChange event handler. JavaScript // using refs class App extends React.Component { constructor() { super(); this.state = { sayings: "" }; } update(e) { this.setState({ sayings: this.refs.anything.value }); } render() { return ( <div> Mukul Says <input type="text" ref="anything" onChange={this.update.bind(this)} /> <br /> <em>{this.state.sayings}</em> </div> ); } } ReactDOM.render(< App />, document.getElementById('root')); Output: Example 2: In this example, we directly define callback function within ref. JavaScript // Filename - App.js // callback used inside ref class App extends React.Component { constructor() { super(); this.state = { sayings: "" }; } update(e) { this.setState({ sayings: this.a.value }); } render() { return ( <div> Mukul Says{" "} <input type="text" ref={(call_back) => { this.a = call_back; }} onChange={this.update.bind(this)} /> <br /> <em>{this.state.sayings}</em> </div> ); } } ReactDOM.render(<App />, document.getElementById("root")); Output: Why useRef over createRef in Function Components?For overcome the disadvantages of createref, prefer useRef. It is a type of hook used to create a reference that hold a value. when updated this value by using function component then does not re-render so that avoid unnecessary re-renders and optimize performance. It store mutable value that persists across renders unlike ref. JavaScript import { useRef } from 'react'; const Refs = ()=>{ let demoRef = useRef(null); function change(){ console.log(demoRef.current); demoRef.current.style.backgroundColor="yellow"; } return ( <div> <h1 ref={demoRef} > Change Color <h1/> <button onClick={change}>Change</button> </div> ); }; Basically createRef is designed for class components. In every render, create a new reference by createRef which is not suitable for function component. When to use refsUsing refs provides a lot of benefits, and improves your web development experience. It is helpful in:Helpful when using third-party libraries.Helpful in animations.Helpful in managing focus, media playback, and text selection.When not to use refsShould not be used with functional components because they don't have instances.Not to be used on things that can be done declaratively.When using a library or framework that provides its methods for managing such as Redux or MobX.ConclusionReact refs are useful to interact with the DOM structure of components. They can directly access and manipulate the DOM elements. This guide teaches the purpose of refs in React, how to create refs, and how to use refs in React with examples. Comment More infoAdvertise with us Next Article ReactJS Rendering Elements immukul Follow Improve Article Tags : Web Technologies ReactJS ReactJS-Basics Similar Reads React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon 8 min read React Introduction ReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.It is developed and maintained by Facebook.The latest version of React is React 19.Uses 8 min read React Environment Setup To run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.We will discuss the following approaches to setup environment in React.Table of Content 3 min read React FundamentalsReact JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi 6 min read ReactJS Babel IntroductionBabel is a JavaScript compiler that converts modern JavaScript code (like ES6+ and JSX) into a backwards-compatible version that older browsers can understand. In the context of React, Babel allows to use modern syntax like JSX and ES6+ features.Transpile ES6+ code: Convert modern JavaScript (ES6 an 5 min read ReactJS Virtual DOMReactJS Virtual DOM is an in-memory representation of the actual DOM (Document Object Model). React uses this lightweight JavaScript object to track changes in the application state and efficiently update the actual DOM only where necessary.What is the Virtual DOM?The Virtual DOM (VDOM) is a lightwe 4 min read React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used 3 min read React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite 5 min read React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc. 5 min read ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the 5 min read ReactJS RefsReactJS Refs are used to access and modify the DOM elements in the React Application. It creates a reference to the elements and uses it to modify them.Table of ContentCreating refs in ReactAccessing Refs in ReactWhy useRef over createRef in Function Components?When to use refsWhen not to use refsWh 4 min read ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are different from DOM elements as React elements are simple JavaScript objects and are effic 3 min read React Conditional RenderingConditional rendering allows dynamic control over which UI elements or content are displayed based on specific conditions. It is commonly used in programming to show or hide elements depending on user input, data states, or system status. This technique improves user experience by ensuring that only 6 min read React ComponentsCode Splitting in ReactCode-Splitting is a feature supported by bundlers like Webpack, Rollup, and Browserify which can create multiple bundles that can be dynamically loaded at runtime.As websites grow larger and go deeper into components, it becomes heavier. This is especially the case when libraries from third parties 4 min read React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render 4 min read ReactJS | Components - Set 2In our previous article on ReactJS | Components we had to discuss components, types of components, and how to render components. In this article, we will see some more properties of components. Composing Components: Remember in our previous article, our first example of GeeksforGeeks's homepage whi 3 min read ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p 4 min read ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio 5 min read React LifecycleIn React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo 7 min read Differences Between Functional Components and Class ComponentsIn React, components are the building blocks of the UI and can be defined as either Functional Components or Class Components. While both serve the same purpose, they differ in syntax, state management, and lifecycle methods. Functional components are simpler and commonly used with React Hooks, whil 4 min read ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon 2 min read React Props & StatesReactJS Methods as PropsIn this article, we will learn about props and passing methods as props. We will also discuss how we can use the child components to pass data to parent components using methods as props.What are props?We know that everything in ReactJS is a component and to pass in data to these components, props a 3 min read ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he 5 min read ReactJS Props - Set 1The react props refer to properties in react that are passed down from parent component to child to render the dynamic content.Till now we have worked with components using static data only. In this article, we will learn about react props and how we can pass information to a Component.What are Prop 5 min read ReactJS Props - Set 2In our previous article ReactJS Props - Set 1 we discussed props, passing and accessing props, passing props from one component to another, etc. In this article, we will continue our discussion on props. So, what if we want to pass some default information using props to our components? React allows 4 min read ReactJS Unidirectional Data FlowIn ReactJS, unidirectional data flow means that data moves in a single directionâfrom the parent component to child componentsâvia props. Changes to the state are always initiated in the parent and propagated downward. Any feedback or data from the child component to the parent is achieved using cal 4 min read ReactJS StateIn React, the state refers to an object that holds information about a component's current situation. This information can change over time, typically as a result of user actions or data fetching, and when state changes, React re-renders the component to reflect the updated UI. Whenever state change 4 min read ReactJS State vs PropsIn React, State allows components to manage and update internal data dynamically, while Props enables data to be passed from a parent component to a child component. Understanding their differences and use cases is essential for developing efficient React applications.State in ReactState is a built- 4 min read Implementing State in React ComponentsIn React State is an object that holds some information which can be changed overtime. Whenever a State is updated it triggers re-rendering of the component. In React components State can be implemented by default in class components and in functional components we have to implement state using hook 3 min read React HooksReact HooksReactJS Hooks are one of the most powerful features of React, introduced in version 16.8. They allow developers to use state and other React features without writing a class component. Hooks simplify the code, make it more readable, and offer a more functional approach to React development. With hoo 10 min read React useState HookThe useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import 5 min read ReactJS useEffect HookThe useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.What is 4 min read Context in ReactContext in React is used to share the data through the React Components without passing the props manually for every level of the component tree. It allows the data to be accessed globally throughout the application and enable efficient state management.In this article, you will be introduced to Rea 4 min read React RouterReact Router is a library for handling routing and navigation in React JS Applications. It allows you to create dynamic routes, providing a seamless user experience by mapping various URLs to components. It enables navigation in a single-page application (SPA) without refreshing the entire page.This 6 min read React JS Types of RoutersWhen creating a React application, managing navigation between different views or pages is important. React Router is the standard library for routing in React, enabling seamless navigation while maintaining the Single Page Application (SPA) behaviour.What is React Router?React Router is a declarati 10 min read ReactJS FragmentsReactJS Fragments are a way to group multiple elements without adding an extra node to the DOM. It allows you to return multiple child elements from a component without wrapping them in a parent container like a <div>.Why Use React Fragments?The primary benefit of Fragments is the capability t 4 min read React AppsCreate ToDo App using ReactJSIn this article, we will create a to-do app to understand the basics of ReactJS. We will be working with class based components in this application and use the React-Bootstrap module to style the components. This to-do list can add new tasks we can also delete the tasks by clicking on them. The logi 3 min read Create a Quiz App using ReactJSIn this article, we will create a quiz application to learn the basics of ReactJS. We will be using class components to create the application with custom and bootstrap styling. The application will start with questions at first and then the score will be displayed at last. Initially, there are only 4 min read Create a Coin Flipping App using ReactJSIn this article, we will build a coin flipping application. In which the user can flip a coin and get a random result from head or tails. We create three components 'App' and 'FlipCoin' and 'Coin'. The app component renders a single FlipCoin component only. FlipCoin component contains all the behind 3 min read How to create a Color-Box App using ReactJS?Basically we want to build an app that shows the number of boxes which has different colors assigned to each of them. Each time the app loads different random colors are assigned. when a user clicks any of the boxes, it changes its color to some different random color that does not equal to its prev 4 min read Dice Rolling App using ReactJSThis article will create a dice-rolling application that rolls two dice and displays a random number between 1 and 6 as we click the button both dice shake and generate a new number that shows on the upper face of the dice (in dotted form as a standard dice). The numbers on the upper face are genera 5 min read Guess the number with ReactIn this article, we will create the guess the number game. In which the computer will select a random number between 1 and 20 and the player will get unlimited chances to guess the number. If the player makes an incorrect guess, the player will be notified whether the guess is is higher or lower tha 3 min read React Connection & DeploymentHow to Deploy Your React Websites on GitHub?Building a web application is always exciting for developers, especially when you step into the programming world for the first time. You build the front end of your application after a lot of struggle, and you want to showcase your skill, your creativity, and of course, your hard work to the world. 6 min read How to Deploy React project on Firebase?When developing any project we must host it somewhere so that the whole world can see our hard-work. Hosting websites can be hectic sometimes, but you don't need to worry as we can now host our React project on Firebase within a minute or two with a very simple setup. The Steps to deploy react proje 2 min read How to deploy React app to Heroku?React is a very popular and widely used library for building User Interfaces. So if you are thinking about deploying your React app to the cloud platform, there are various choices for doing that such as AWS EC2 or Heroku. But for testing your React app, Heroku will be the best option as it is free 3 min read How to deploy React app to Surge ?React stands out as a widely embraced library for crafting User Interfaces. When it comes to deploying your static React app effortlessly, the surge package comes in handy, enabling you to publish web apps to a CDN seamlessly with just one command. Prerequisites:Installation of Node.js on WindowsIns 3 min read How to deploy simple frontend server-less (static) React applications on NetlifyNetlify is one of the most popular hosting services that specialize in hosting server-less services for web applications and static websites. It is a web development program that quadruples productivity. By unifying the elements of the modern decoupled web, from local development to advanced edge lo 6 min read React ExercisesReact Exercises, Practice Questions and SolutionsReactJS Exercises offers interactive challenges, tracks your learning journey, and helps you sharpen your React skills with our engaging platform. Ideal for both beginners and advanced developers, you can level up your React proficiency at your own pace. Start coding and building dynamic application 4 min read Like